实际项目中,保证进程不被完全彻底杀死,是不可能的。
单进程守护场景:home键,直接杀死进程,进程仍然处于运行状态;
适用手机类型:50%的低中端手机,小米做的太好了,根本无法实现。
单进程守护原理:应用启动开启一个service,并在service的onDestroy()方法里发送广播,BroadcastReccevier里重新startService;
代码实现:
1、创建Service服务:
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTime();
//返回值设置,保证后台一直运行;
return START_STICKY;
}
/**
* 当进程被销毁时,发送广播重启服务。
*/
@Override
public void onDestroy() {
super.onDestroy();
Intent broadCastIntent=new Intent("com.example.xiaoke.singleservice.ServiceRestartBroadCastReceiver.restart");
sendBroadcast(broadCastIntent);
stopTime();
}
2、创建braodCastRecevier,接收到广播重启服务:
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"onReceive");
context.startService(new Intent(context,RecreatService.class));
}
3、清单文件配置:
<service
android:name=".RecreatService"
android:enabled="true"
android:exported="true"></service>
<receiver
android:name=".ServiceRestartBroadCastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.xiaoke.singleservice.ServiceRestartBroadCastReceiver.restart"></action>
</intent-filter>
</receiver>
ok项目结束,实际测试一下。关于源码,请留下邮箱。