1.在service中重写下面的方法,这个方法有三个返回值, START_STICKY是service被kill掉后自动重写创建
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
在setting里kill掉,没能重启
2.在Service的onDestroy()中重启Service.
public void onDestroy() {
Intent localIntent = new Intent();
localIntent.setClass(this, MyService.class); //销毁时重新启动Service
this.startService(localIntent);
}
通过别的应用,直接kill掉我的应用时,是不会调用这个方法的
但是在settings 中stop service,onDestroy方法中,调用startService进行Service的重启。
3.settings中force stop 应用捕捉系统进行广播(action为android.intent.action.PACKAGE_RESTARTED)
- public class ProtectorHelperReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- String pkg = "com.innofidei.myprotector";// 被kill的应用的包名
- String action = pkg + ".action.START_SERVICE";// 重启service的acition
- String str = intent.getData().toString().toLowerCase().replace("package:", "");
- String data = intent.getAction();
- if (str != null && str.equals(pkg)) {
- if (data != null && data.equals("android.intent.action.PACKAGE_REMOVED")) {
- File file = new File("/sdcard/" + context.getPackageName() + "/ProtectorHelper.apk");
- file.delete();
- file.getParentFile().delete();
- Intent intent2 = new Intent(context, UninstallActivity.class);
- intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- context.startActivity(intent2);
- } else {
- context.sendBroadcast(new Intent(action));// 通知应用重启service
- }
- }
- }
- }
提升service的优先级
setForeground(true) ;