Android 后臺定時任務

項目中需要做一個定時本地通知,本文是自己code時所遇到的問題以及解決方案的總結(jié),其中借鑒了一些文章中的解決方式,文章后有借鑒文章鏈接和項目github地址。
Android 中的定時任務一般有兩種實現(xiàn)方式,一種是使用 Java API 里提供的 Timer 類,一種是使用 Android 的 Alarm 機制。這兩種方式在多數(shù)情況下都能實現(xiàn)類似的效果。
  • Timer并不太適用于那些需要長期在后臺運行的定時任務。為了能讓電池更加耐用,每種手機都會有自己的休眠策略,Android 手機就會在長時間不操作的情況下自動讓 CPU 進入到睡眠狀態(tài),這就有可能導致 Timer 中的定時任務無法正常運行。
  • Alarm具有喚醒 CPU 的功能,即可以保證每次需要執(zhí)行定時任務的時候 CPU 都能正常工作。

Alarm主要是借助AlarmManager類來實現(xiàn),Android 官方文檔對AlarmManager解釋如下

該類提供對系統(tǒng)報警服務的訪問。這些允許您安排您的應用程序在將來的某個時間運行。當報警熄滅時,已注冊的意圖由系統(tǒng)進行廣播,如果尚未運行,則自動啟動目標應用程序...
...
注意:從API 19(KITKAT)開始,報警傳遞不準確:操作系統(tǒng)將移動報警,以最大限度地減少喚醒和電池使用。有新的API支持需要嚴格交付保證的應用程序
...

設(shè)置定時任務,API大于19會有報警時間不準確,API大于23時Doze模式系統(tǒng)將嘗試減少設(shè)備的喚醒頻率推遲后臺作業(yè)可能導致無法執(zhí)行,我們需要根據(jù)版本分別適配。同時用BroadcastReceiver接受提醒并執(zhí)行任務

    Intent alarmIntent = new Intent();
    alarmIntent.setAction(TamingReceiver.ALARM_WAKE_ACTION);
    PendingIntent operation = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(operation);
    long triggerAtMillis = task.triggerAtMillis();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), operation);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), operation);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), operation);
    }
    //接受任務提醒
    public class TamingReceiver extends BroadcastReceiver {
    
        public static final String ALARM_WAKE_ACTION = "youga.tamingtask.taming.ALARM_WAKE_ACTION";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive()--Action:" + intent.getAction());
        }
    }

實際使用時AlarmManager無論在應用是否被關(guān)閉都能正常執(zhí)行,但這僅限于原生Android系統(tǒng)。國產(chǎn)定制Android系統(tǒng)小米、魅族、華為等等都會對AlarmManager喚醒做限制,導致應用被關(guān)閉后無法正常執(zhí)行。此時我們需要做的就是應用?;?/h4>

應用?;羁梢苑譃閮蓚€方面,一. 提供進程優(yōu)先級,降低進程被殺死的概率,二. 在進程被殺死后,進行拉活

提升進程優(yōu)先級的方案可分為Activity 提升權(quán)限, Notification 提升權(quán)限

  • Activity 提升權(quán)限有網(wǎng)傳QQ一像素Activity方案,該方案涉及觸摸時間攔截,各種狀態(tài)監(jiān)聽操作難度復雜。

  • Notification 提升權(quán)限,API小于18可以直接設(shè)置前臺Notification。API大于18利用系統(tǒng)漏洞,兩個Service共同設(shè)置同一個ID 的前臺Notification,并關(guān)閉其中一個Service,Notification消失,另一個Service優(yōu)先級不變,此漏洞API=24時被修復

     public void onCreate() {
          super.onCreate();
          Log.d(TAG, "onCreate()");
    
          Daemon.run(TamingService.this, TamingService.class, Daemon.INTERVAL_ONE_MINUTE);
    
          Intent service = new Intent(this, TamingGuardService.class);
          startService(service);
    
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
              startForeground(GRAY_SERVICE_ID, new Notification());
          } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
              Intent innerIntent = new Intent(this, TamingInnerService.class);
              startService(innerIntent);
              startForeground(GRAY_SERVICE_ID, new Notification());
          } else {
              // TODO: 2017/9/22 0022
    
          }
     }
    

進程死后拉活的方案可分為系統(tǒng)廣播拉活,利用系統(tǒng)Service機制拉活,利用Native進程拉活

  • 廣播接收器被管理軟件、系統(tǒng)軟件通過“自啟管理”等功能禁用的場景無法接收到廣播,從而無法自啟,系統(tǒng)廣播事件不可控,只能保證發(fā)生事件時拉活進程,但無法保證進程掛掉后立即拉活。

      <receiver
          android:name=".taming.WakeUpReceiver"
          android:process=":Taming">
          <intent-filter>
              <action android:name="android.intent.action.USER_PRESENT"/>
              <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
              <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
          </intent-filter>
          <intent-filter>
              <action android:name="android.intent.action.BOOT_COMPLETED"/>
              <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
          </intent-filter>
          <intent-filter>
              <action android:name="android.intent.action.PACKAGE_ADDED"/>
              <action android:name="android.intent.action.PACKAGE_REMOVED"/>
    
              <data android:scheme="package"/>
          </intent-filter>
      </receiver>
    
  • 同時我們啟動另個守護GuardService監(jiān)聽這個Service狀態(tài),如果發(fā)現(xiàn)這個被異常Service關(guān)閉則啟動這個Service,API小于21我們用AlarmManager重復監(jiān)聽,API大于21我們使用JobScheduler監(jiān)聽,然而JobScheduler在API大于24時Doze模式會因為電池優(yōu)化而無法正常執(zhí)行,我們需要忽略電池優(yōu)化

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    //守護GuardService
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(0, new ComponentName(getPackageName(), JobSchedulerService.class.getName()));
        builder.setPeriodic(JOB_INTERVAL); //每隔60秒運行一次
        //Android 7.0+ 增加了一項針對 JobScheduler 的新限制,最小間隔只能是下面設(shè)定的數(shù)字
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.setPeriodic(JobInfo.getMinPeriodMillis(), JobInfo.getMinFlexMillis());
        }
        builder.setRequiresCharging(true);
        builder.setPersisted(true);  //設(shè)置設(shè)備重啟后,是否重新執(zhí)行任務
        builder.setRequiresDeviceIdle(true);

        if (jobScheduler.schedule(builder.build()) <= 0) {
            Log.w("init", "jobScheduler.schedule something goes wrong");
        }
    } else {
        //發(fā)送喚醒廣播來促使掛掉的UI進程重新啟動起來
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, TamingService.class);
        alarmIntent.setAction(TamingService.GUARD_INTERVAL_ACTION);
        PendingIntent operation = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ALARM_INTERVAL, operation);
    }
    
   //忽略電池優(yōu)化
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
       PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
       boolean ignoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(context.getPackageName());
       if (!ignoringBatteryOptimizations) {
           Intent dozeIntent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
           dozeIntent.setData(Uri.parse("package:" + context.getPackageName()));
           startActivity(dozeIntent);
       }
   }
  • 利用Native進程拉活,我們采用開源的守護進程庫。Android-AppDaemon。該方案主要適用于 Android5.0 以下版本手機。該方案不受 forcestop 影響,被強制停止的應用依然可以被拉活,在 Android5.0 以下版本拉活效果非常好。對于 Android5.0 以上手機,系統(tǒng)雖然會將native進程內(nèi)的所有進程都殺死,這里其實就是系統(tǒng)“依次”殺死進程時間與拉活邏輯執(zhí)行時間賽跑的問題,如果可以跑的比系統(tǒng)邏輯快,依然可以有效拉起。

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");
    
        Daemon.run(TamingService.this, TamingService.class, Daemon.INTERVAL_ONE_MINUTE);
    }
    

綜上所述,Android原生系統(tǒng)使用AlarmManager執(zhí)行定時任務無需處于運行中,但是手機重啟后會清除所有Alarm,所以最終導向還是應用?;?。

非原生Android系統(tǒng)會對系統(tǒng)修改我們需要各種方式配合,保證最大幾率?;?。一Notification 提升權(quán)限,二監(jiān)聽解鎖監(jiān)控電池電量和充電狀態(tài),開機廣播,網(wǎng)絡變化,應用安裝、卸載,三守護GuardService監(jiān)聽,四利用Native進程拉活。然而這四中方式都無法保證百分百?;睿覀冞€需要根據(jù)各機型適配,引導用戶加入手機白名單,每個手機廠商各個版本白名單方式都會變化,適配路漫漫其修遠兮,只能祈禱國內(nèi)Android生態(tài)越來越好吧。

        //華為 自啟管理
        Intent huaweiIntent = new Intent();
        huaweiIntent.setAction("huawei.intent.action.HSM_BOOTAPP_MANAGER");

        //華為 鎖屏清理
        Intent huaweiGodIntent = new Intent();
        huaweiGodIntent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));

        //小米 自啟動管理
        Intent xiaomiIntent = new Intent();
        xiaomiIntent.setAction("miui.intent.action.OP_AUTO_START");
        xiaomiIntent.addCategory(Intent.CATEGORY_DEFAULT);

        //小米 神隱模式
        Intent xiaomiGodIntent = new Intent();
        xiaomiGodIntent.setComponent(new ComponentName("com.miui.powerkeeper", "com.miui.powerkeeper.ui.HiddenAppsConfigActivity"));
        xiaomiGodIntent.putExtra("package_name", context.getPackageName());
        xiaomiGodIntent.putExtra("package_label", getApplicationName(context));

        //三星 5.0/5.1 自啟動應用程序管理
        Intent samsungLIntent = context.getPackageManager().getLaunchIntentForPackage("com.samsung.android.sm");

        //三星 6.0+ 未監(jiān)視的應用程序管理
        Intent samsungMIntent = new Intent();
        samsungMIntent.setComponent(new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.battery.BatteryActivity"));

        //魅族 自啟動管理
        Intent meizuIntent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        meizuIntent.addCategory(Intent.CATEGORY_DEFAULT);
        meizuIntent.putExtra("packageName", context.getPackageName());

        //魅族 待機耗電管理
        Intent meizuGodIntent = new Intent();
        meizuGodIntent.setComponent(new ComponentName("com.meizu.safe", "com.meizu.safe.powerui.PowerAppPermissionActivity"));

        //Oppo 自啟動管理
        Intent oppoIntent = new Intent();
        oppoIntent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));

        //Oppo 自啟動管理(舊版本系統(tǒng))
        Intent oppoOldIntent = new Intent();
        oppoOldIntent.setComponent(new ComponentName("com.color.safecenter", "com.color.safecenter.permission.startup.StartupAppListActivity"));

        //Vivo 后臺高耗電
        Intent vivoGodIntent = new Intent();
        vivoGodIntent.setComponent(new ComponentName("com.vivo.abe", "com.vivo.applicationbehaviorengine.ui.ExcessivePowerManagerActivity"));

        //金立 應用自啟
        Intent gioneeIntent = new Intent();
        gioneeIntent.setComponent(new ComponentName("com.gionee.softmanager", "com.gionee.softmanager.MainActivity"));

        //樂視 自啟動管理
        Intent letvIntent = new Intent();
        letvIntent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));

        //樂視 應用保護
        Intent letvGodIntent = new Intent();
        letvGodIntent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.BackgroundAppManageActivity"));

        //酷派 自啟動管理
        Intent coolpadIntent = new Intent();
        coolpadIntent.setComponent(new ComponentName("com.yulong.android.security", "com.yulong.android.seccenter.tabbarmain"));

        //聯(lián)想 后臺管理
        Intent lenovoIntent = new Intent();
        lenovoIntent.setComponent(new ComponentName("com.lenovo.security", "com.lenovo.security.purebackground.PureBackgroundActivity"));

        //聯(lián)想 后臺耗電優(yōu)化
        Intent lenovoGodIntent = new Intent();
        lenovoGodIntent.setComponent(new ComponentName("com.lenovo.powersetting", "com.lenovo.powersetting.ui.Settings$HighPowerApplicationsActivity"));

        //中興 自啟管理
        Intent zteIntent = new Intent();
        zteIntent.setComponent(new ComponentName("com.zte.heartyservice", "com.zte.heartyservice.autorun.AppAutoRunManager"));

        //中興 鎖屏加速受保護應用
        Intent zteGodIntent = new Intent();
        zteGodIntent.setComponent(new ComponentName("com.zte.heartyservice", "com.zte.heartyservice.setting.ClearAppSettingsActivity"));

        //錘子 自啟動權(quán)限管理 //{cmp=com.smartisanos.security/.invokeHistory.InvokeHistoryActivity (has extras)} from uid 10070 on display 0
        Intent smartIntent = new Intent();
        smartIntent.putExtra("packageName", context.getPackageName());
        smartIntent.setComponent(new ComponentName("com.smartisanos.security", "com.smartisanos.security.invokeHistory.InvokeHistoryActivity"));

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容