您的位置:首页 > 其它

如何保证service不被杀掉

2016-04-14 17:17 295 查看
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

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  

                        }  

                }  

        }  

}  

4. 借助第三方应用kill掉running task

提升service的优先级
 setForeground(true) ;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: