美文网首页
Android Service防杀

Android Service防杀

作者: JFang | 来源:发表于2018-09-11 11:58 被阅读0次

    一.在onStartCommand方法,返回START_STICKY

    1、START_STICKY

    在运行onStartCommand后service进程被kill后,那将保留在开始状态,但是不保留那些传入的intent。不久后service就会再次尝试重新创建,因为保留在开始状态,在创建 service后将保证调用onstartCommand。如果没有传递任何开始命令给service,那将获取到null的intent。

    2、START_NOT_STICKY

    在运行onStartCommand后service进程被kill后,并且没有新的intent传递给它。Service将移出开始状态,并且直到新的明显的方法(startService)调用才重新创建。因为如果没有传递任何未决定的intent那么service是不会启动,也就是期间onstartCommand不会接收到任何null的intent。

    3、START_REDELIVER_INTENT

    在运行onStartCommand后service进程被kill后,系统将会再次启动service,并传入最后一个intent给onstartCommand。直到调用stopSelf(int)才停止传递intent。如果在被kill后还有未处理好的intent,那被kill后服务还是会自动启动。因此onstartCommand不会接收到任何null的intent。

    二.通过Notification 提高进程优先级

    在onStartCommand中创建Notification是Service变成前台进程,代码如下:
    Notification notification = new Notification(R.drawable.ic_launcher,
    getString(R.string.app_name), System.currentTimeMillis());

         PendingIntent pendingintent = PendingIntent.getActivity(this, 0,
         new Intent(this, AppMain.class), 0);
         notification.setLatestEventInfo(this, "uploadservice", "请保持程序在后台运行",
         pendingintent);
         startForeground(0x111, notification);
    

    三.onDestroy方法里重启service

    service +broadcast 方式,就是当service走ondestory的时候,发送一个自定义的广播,当收到广播的时候,重新启动service;

               <intent-filter>
                   <action android:name="android.intent.action.BOOT_COMPLETED" />
                   <action android:name="android.intent.action.USER_PRESENT" />
                   <action android:name="com.dbjtech.waiqin.destroy" />//这个就是自定义的action
               </intent-filter>
           </receiver>
    

    在onDestroy时:

        @Override
        public void onDestroy() {
            stopForeground(true);
            Intent intent = new Intent("com.dbjtech.waiqin.destroy");
            sendBroadcast(intent);
            super.onDestroy();
        }
    

    在BootReceiver里

    public class BootReceiver extends BroadcastReceiver {
     
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.dbjtech.waiqin.destroy")) {
                //TODO
                //在这里写重新启动service的相关操作
                    startUploadService(context);
            }
     
        }
     
    }
    

    也可以直接在onDestroy()里startService

        @Override
        public void onDestroy() {
     
             Intent sevice = new Intent(this, MainService.class);
             this.startService(sevice);
     
            super.onDestroy();
        }
    

    相关文章

      网友评论

          本文标题:Android Service防杀

          本文链接:https://www.haomeiwen.com/subject/bhzygftx.html