Service生命周期
- 通过startService
Service会经历 onCreat->onStart->onDestroy,调用stopService方法 的时候直接OnDestroy。如果调用者没有stopService直接退出,那Service会在后台继续运行知道下次再启动时调用stopService退出服务 - 通过bindService
只会运行onCreate()此时service与程序绑定在一起,如果程序退出了,service会调用onUnBind->onDestroyed,service与程序共存亡 - 另外如果这几种方法交织到了一起,可以遵循以下原则
Service的onCreate只会调用一次。如果先start,那bind时就直接onBind。如果先bind,那么start时直接start,start的stopService无法使用,只能先unBindService,再使用stopService。
创建Service
Service类
public class MySever extends Service{
private int StatusCode;
public MyServiceBinder myServiceBinder = new MyServiceBinder();
//继承Binder类,编写getStatusCode方法,以获取状态码
public class MyServiceBinder extends Binder{
public int getStatusCode(){
return StatusCode;
}
}
public IBinder onBind(Intent intent){
return myServiceBinder;
}
public void onCreate (){
super.onCreat();
Toast.makeToast(this,"this is onCreate",Toast.LENGTH_LONG).show();
}
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"this is ondestroy",Toast.LENGTH_LONG).show();
}
}
配置运行入口
<service android:name="MyService">
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE"/>
</intent-filter>
</service>
注意要给与相应的权限:
<uses-permission android:name="com.permission.MY_SERVICE_PERMISSION">
</uses-permission>
使用Service
- startService法
Intent severintent = new Intent();
severintent.setAction("android.intent.action.RESPOND_VIA_MESSAGE");
startService(severintent);//开始服务
stopService(severintent);//停止服务
使用简单方便,程序退出前,若为调用stopService方法,则Service会继续运行,直到下次程序调用stopService方法
- 绑定Service法
ServiceConnection con = new ServiceConnection() {
@Override
int statusCode;
MySever.MyServiceBinder myServiceBinder = new MyServiceBinder();
public void onServiceConnected(ComponentName name, IBinder service) {
myServiceBinder = (MyService.MyServiceBinder)service;//获取Binder对象,强转为MyServiceBinder对象
statusCode = myServiceBinder.getStatusCode();//应用与service间的通信,返回状态码
Log.i("Service", "onServiceConnected:Connected "+statusCode);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("Service", "onServiceConnected: Disconnected");
}
};
bindService(new Intent("android.intent.action.RESPOND_VIA_MESSAGE"),con, Context.BIND_AUTO_CREATE);//绑定service
Service与应用之间通过IBinder对象进行通信
提高Service优先级
由于android系统有着一套内存管理服务 ,系统会自行终止一些它认为不重要的程序或服务,若遇到了这种情况,我们的Service多半会被杀掉。如果增加其优先级,就能多苟一会……默认启动时,Service优先级为background,当前运行的Activity一般为Foreground,在Service中使用setForeground(true)可使优先级提高到当前于activity相当的程度。