一、Service的基本用法
1.定义一个Service
public class MyService extends Service {
public static final String TAG = "MyService";
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"onCreate executed");
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d(TAG,"onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy() executed");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
onCreate()方法会在Service第一次创建的时候调用,onStartCommand()方法会在每次Service启动的时候调用,onDestory()方法会在Service销毁的时候调用。
Service启动立刻执行某个动作,可以将逻辑写在onStartCommand()方法里。在onDestory()方法中回收不再使用的资源。
Service需要在AndroidManifest.xml文件中进行注册才能生效。
2.启动和停止Service
Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);
在Service中创建一个Binder实例,提供一系列方法。在Activity中绑定Service,在ServiceConnection中获取该Binder实例,执行需要的方法。
private ServiceConnection connection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
onServiceConnected():Activity和Service成功绑定时调用。
onServiceDisconneced():Activity和Service解除绑定时调用。
绑定Service
Intent bindIntent = new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
bindService()方法接受三个参数,第一个参数是Intent,第二个参数是ServiceConnection,第三个参数是个标记位,传入BIND_AUTO_CREATE表示Activity绑定Service后自动创 建Service。
unbindService(connection);
二、Service的生命周期
调用Context的startService()方法,如果Service是第一次被创建,则先执行onCreate()方法,然后执行onStartCommand()方法,直到stopService()或stopSelf()调用后执行onDestory()方法。如果Service已经创建过,则每调用一次startService()方法,onStartCommand()方法就会执行一次。
调用Context的bindService()方法,如果Service是第一次创建,则先执行onCreate()方法,然后执行onBind()方法,直到stopService()或stopSelf()调用后执行onDestory()方法。
如果Service已经创建过,则onCreate()方法和onBind()方法不会再执行。
如果一起调用了startService()和bindService()方法,则需要同时调用stopService和unBindService()方法onDestory()才可以执行。
前台Service
Service的系统优先级较低,当系统出现内存不足的时候,就有可能回收掉正在后台运行的Service。如果希望Service一直保持运行状态,不会由于系统内存不足的原因导致被回收,就可以考虑使用前台Service。
IntentService
IntentService是一个异步的,会自动停止的Service,集开线程和自动停止于一身。