如何保证service不被杀掉

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)

[java]  view plain  copy
  1. public class ProtectorHelperReceiver extends BroadcastReceiver {  
  2.         @Override  
  3.         public void onReceive(Context context, Intent intent) {  
  4.                 String pkg = "com.innofidei.myprotector";// 被kill的应用的包名  
  5.                 String action = pkg + ".action.START_SERVICE";// 重启service的acition  
  6.                 String str = intent.getData().toString().toLowerCase().replace("package:""");  
  7.                 String data = intent.getAction();    
  8.                 if (str != null && str.equals(pkg)) {  
  9.                         if (data != null && data.equals("android.intent.action.PACKAGE_REMOVED")) {  
  10.                                 File file = new File("/sdcard/" + context.getPackageName() + "/ProtectorHelper.apk");  
  11.                                 file.delete();  
  12.                                 file.getParentFile().delete();  
  13.                                 Intent intent2 = new Intent(context, UninstallActivity.class);  
  14.                                 intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  15.                                 context.startActivity(intent2);  
  16.                         } else {  
  17.                                 context.sendBroadcast(new Intent(action));// 通知应用重启service  
  18.                         }  
  19.                 }  
  20.         }  
  21. }  
4. 借助第三方应用kill掉running task

提升service的优先级

 setForeground(true) ;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值