android的服务分为本地服务和远程服务。前者用于应用程序内部,后者用于android系统内部各个应用程序之间。远程服务需要用到AIDL接口,前面已有文章论述,不再赘述。很多时候,我们都想要自定义一个自己的本地服务,下面简单介绍一下具体的实现方法。
步骤一:
首先创建一个myService的类,该类需要继承Service类。此时ADT会提示你添加未实现的方法
onBind(Intent Intent)函数。该函数的参数Intent就是用来绑定这个服务的Intent,返回一个IBinder对象。
public class MainService extends Service {
private ServiceBinder sBinder = new ServiceBinder();
@Override
public IBinder onBind(Intent intent) {
Log.i("msg","Mainservice.onBind");
return sBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("msg","Mainservice.onUnbind");
return false;
}
@Override
public void onRebind(Intent intent) {
Log.i("msg","Mainservice.onRebind");
}
@Override
public void onCreate() {
Log.i("msg","Mainservice.onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("msg","Mainservice.onStart");
}
//服务的绑定,绑定服务的activity要调用它得到服务
public class ServiceBinder extends Binder {
public MainService getService() {
return MainService.this;
}
}
定义一个服务类时,上面红色部分是必须存在的东西。如果想在服务中添加自己的东西,比如开启线程之类的,可以在oncreate()函数或者onStart()函数中进行定义。
步骤二:定义一个需要绑定服务的activity
启动一个Service有两种方法,start和bind,都是通过Intent调用的。
方式一:直接开启或关闭服务(适合不与activity进行交互的场景)
定义开启/关闭服务的方法,并在合适的地方调用即可
private void startService() {
Intent i = new Intent(this, myService.class);
this.startService(i);
}
private void stopService() {
Intent i = new Intent(this, myService.class);
this.stopService(i);
}
方式二:bind,需要在activity中定义一个ServiceConnection对象,用来把Activity和特定的Service绑定起来。然后再在Activity的oncreate函数中调用this.bindService(intent,sconnection,context.BIND_AUTO_CREATE)和this.startService(intent)来开启服务。
private ServiceConnection sConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = ((MainService.ServiceBinder) service).getService();
Log.i("msg","Service connected to activity...");
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mService = null;
Log.i("msg","Service disconnected to activity...");
}
};
步骤三:在AndroidManifest.xml文件中添加对该服务的声明:
<service
android:name="com.example.service.MainService"
android:enabled="true" />
service的生命周期:
Service的生命周期只有onCreate、onStart、onDestroy三个。
通过方式一:
开启服务时: Service经历 onCreate --->onStart
关闭服务时:直接onDestroy
如果调用者直接退出而没有关闭服务,则Service一直在后台运行,等到下次调用关闭时再停止运行。
通过方式二:
开启: context.bindService()->onCreate()->onBind()->Servicerunning
关闭:onUnbind() ->onDestroy()->service stop
PS:service的onCreate()只会被调用一次。