Service应用总结

    如果把Activity比喻为前台程序,那么Service就是后台程序,Service的整个生命周期都只会在后台执行。Service跟 Activity一样也由Intent调用。
在工程里想要添加一个Service,先新建继承Service的类,然后到 AndroidManifest.xml -> Application ->Application Nodes中的Service标签中添加:
一、添加Service声明
<service android:name=".CounterService" android:enabled="true">  
    </service> 
二、两种方式启动service
Service要由Activity通过startService 或者 bindService来启动,Intent负责传递参数。
startService与bindService都可以启动Service,它们两者的区别就是使Service的周期改变。
(1) startService启动的Service必须要有stopService来结束Service,不调用stopService则会造成Activity结束了而Service还运行着。
(2) bindService启动的Service可以由unbindService来结束,也可以在 Activity结束之后(onDestroy)自动结束。

1、Activity通过startService 

参考:http://android.tgbus.com/Android/tutorial/201107/359322.shtml

启动一个Service的过程如下:context.startService()  ->onCreate()- >onStart()->Service running其中onCreate()

可以进行一些服务的初始化工作,onStart()则启动服务。
停止一个Service的过程如下:context.stopService() | ->onDestroy() ->Service stop
接下来的实例是一个利用后台服务播放音乐的小例子,点击start运行服务,点击stop停止服务。
1.1 创建Service类

package test.cbl.srv;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = "MyService";
    MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onCreate");

        player = MediaPlayer.create(this,R.raw.mine);
        player.setLooping(false);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onDestroy");
        player.stop();
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onStart");
        player.start();
    }
}

1.2 Activity中启动Service

package test.cbl.srv;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServiceDemo extends Activity implements OnClickListener {
private static final String TAG = "ServiceDemo";
Button buttonStart, buttonStop;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);

}
public void onClick(View src){
switch (src.getId()) {
case R.id.buttonStart:
Log.i(TAG, "onClick: starting service");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.i(TAG, "onClick: stopping service");
stopService(new Intent(this, MyService.class));
break;
}
}
}

1.3 string.xml字符串定义

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">播放器服务</string>
<string name="start">Start</string>
<string name="stop">Stop</string>
<string name="services_demo">Service Demo</string>
</resources>

1.4  main.xml布局文件layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView 
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/services_demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="@string/start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>

1.5  Manifest.xml 添加Service声明

<service android:enabled="true" android:name=".MyService"/>

2、bindService方式启动Service

2.1 Activity中Oncreate中:
//建立和service的通讯
            Intent bindIntent = new Intent(MainActivity.this, CounterService.class);  
            bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);  


2.2 类中创建connection对象
 private ServiceConnection serviceConnection = new ServiceConnection() {  
            public void onServiceConnected(ComponentName className, IBinder service) {  
            counterService = ((CounterService.CounterBinder)service).getService();  
              
            Log.i(LOG_TAG, "Counter Service Connected");  
            }  
            public void onServiceDisconnected(ComponentName className) {  
            counterService = null;  
            Log.i(LOG_TAG, "Counter Service Disconnected");  
            }  
        };  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Android开发中,Service是一个非常重要的组件,用于在后台执行长时间运行的操作,不与用户交互。以下是本次实验的总结: 1. Service生命周期 Service的生命周期包括:onCreate()、onStartCommand()、onBind()、onUnbind()、onRebind()和onDestroy()。开发者可以根据不同的业务需求实现这些生命周期函数。 2. Service的启动和停止 Service的启动和停止有两种方式:使用startService()和stopService()方法来启动和停止Service;使用bindService()和unbindService()方法来绑定和解绑Service。需要注意的是,使用startService()方法启动的Service会一直运行,直到调用stopService()方法或者Service自己调用stopSelf()方法;使用bindService()方法启动的Service会在与之绑定的Activity销毁时自动停止。 3. Service的通信 Service可以和Activity之间进行通信,可以使用Intent传递数据,也可以使用Messenger进行通信。如果需要在Service中执行耗时操作,需要在Service中开启一个新的线程来执行,否则会阻塞主线程。 4. Service的注册 在AndroidManifest.xml文件中注册Service,可以使用以下代码: ``` <service android:name=".MyService" /> ``` 5. Service的注意事项 在使用Service时,需要注意以下几点: - Service是在主线程中运行的,不能在Service中执行耗时操作,否则会阻塞主线程。 - Service一旦启动就会一直运行,需要在适当的时候停止Service。 - Service可以和Activity之间进行通信,需要根据具体的业务需求选择合适的通信方式。 总之,Service是Android开发中非常重要的组件,掌握其使用方法和生命周期函数对于开发高质量的Android应用程序非常有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值