項(xiàng)目中需要做一個(gè)定時(shí)本地通知,本文是自己code時(shí)所遇到的問題以及解決方案的總結(jié)疚漆,其中借鑒了一些文章中的解決方式酣胀,文章后有借鑒文章鏈接和項(xiàng)目github地址。
Android 中的定時(shí)任務(wù)一般有兩種實(shí)現(xiàn)方式娶聘,一種是使用 Java API 里提供的 Timer 類灵临,一種是使用 Android 的 Alarm 機(jī)制。這兩種方式在多數(shù)情況下都能實(shí)現(xiàn)類似的效果趴荸。
- Timer并不太適用于那些需要長期在后臺(tái)運(yùn)行的定時(shí)任務(wù)儒溉。為了能讓電池更加耐用,每種手機(jī)都會(huì)有自己的休眠策略发钝,Android 手機(jī)就會(huì)在長時(shí)間不操作的情況下自動(dòng)讓 CPU 進(jìn)入到睡眠狀態(tài)顿涣,這就有可能導(dǎo)致 Timer 中的定時(shí)任務(wù)無法正常運(yùn)行。
- Alarm具有喚醒 CPU 的功能酝豪,即可以保證每次需要執(zhí)行定時(shí)任務(wù)的時(shí)候 CPU 都能正常工作涛碑。
Alarm主要是借助AlarmManager類來實(shí)現(xiàn),Android 官方文檔對(duì)AlarmManager解釋如下
該類提供對(duì)系統(tǒng)報(bào)警服務(wù)的訪問孵淘。這些允許您安排您的應(yīng)用程序在將來的某個(gè)時(shí)間運(yùn)行蒲障。當(dāng)報(bào)警熄滅時(shí),已注冊(cè)的意圖由系統(tǒng)進(jìn)行廣播,如果尚未運(yùn)行揉阎,則自動(dòng)啟動(dòng)目標(biāo)應(yīng)用程序...
...
注意:從API 19(KITKAT)開始庄撮,報(bào)警傳遞不準(zhǔn)確:操作系統(tǒng)將移動(dòng)報(bào)警,以最大限度地減少喚醒和電池使用毙籽。有新的API支持需要嚴(yán)格交付保證的應(yīng)用程序
...
設(shè)置定時(shí)任務(wù)洞斯,API大于19會(huì)有報(bào)警時(shí)間不準(zhǔn)確,API大于23時(shí)Doze模式系統(tǒng)將嘗試減少設(shè)備的喚醒頻率推遲后臺(tái)作業(yè)可能導(dǎo)致無法執(zhí)行坑赡,我們需要根據(jù)版本分別適配烙如。同時(shí)用BroadcastReceiver接受提醒并執(zhí)行任務(wù)
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);
}
//接受任務(wù)提醒
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());
}
}
實(shí)際使用時(shí)AlarmManager無論在應(yīng)用是否被關(guān)閉都能正常執(zhí)行,但這僅限于原生Android系統(tǒng)毅否。國產(chǎn)定制Android系統(tǒng)小米亚铁、魅族、華為等等都會(huì)對(duì)AlarmManager喚醒做限制螟加,導(dǎo)致應(yīng)用被關(guān)閉后無法正常執(zhí)行刀闷。此時(shí)我們需要做的就是應(yīng)用保活
應(yīng)用毖銮ǎ活可以分為兩個(gè)方面,一. 提供進(jìn)程優(yōu)先級(jí)甸昏,降低進(jìn)程被殺死的概率,二. 在進(jìn)程被殺死后徐许,進(jìn)行拉活
提升進(jìn)程優(yōu)先級(jí)的方案可分為Activity 提升權(quán)限, Notification 提升權(quán)限
Activity 提升權(quán)限有網(wǎng)傳QQ一像素Activity方案,該方案涉及觸摸時(shí)間攔截施蜜,各種狀態(tài)監(jiān)聽操作難度復(fù)雜。
-
Notification 提升權(quán)限雌隅,API小于18可以直接設(shè)置前臺(tái)Notification翻默。API大于18利用系統(tǒng)漏洞,兩個(gè)Service共同設(shè)置同一個(gè)ID 的前臺(tái)Notification恰起,并關(guān)閉其中一個(gè)Service修械,Notification消失,另一個(gè)Service優(yōu)先級(jí)不變,此漏洞API=24時(shí)被修復(fù)
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 } }
進(jìn)程死后拉活的方案可分為系統(tǒng)廣播拉活检盼,利用系統(tǒng)Service機(jī)制拉活肯污,利用Native進(jìn)程拉活
-
廣播接收器被管理軟件、系統(tǒng)軟件通過“自啟管理”等功能禁用的場(chǎng)景無法接收到廣播吨枉,從而無法自啟蹦渣,系統(tǒng)廣播事件不可控,只能保證發(fā)生事件時(shí)拉活進(jìn)程貌亭,但無法保證進(jìn)程掛掉后立即拉活柬唯。
<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>
同時(shí)我們啟動(dòng)另個(gè)守護(hù)GuardService監(jiān)聽這個(gè)Service狀態(tài),如果發(fā)現(xiàn)這個(gè)被異常Service關(guān)閉則啟動(dòng)這個(gè)Service,API小于21我們用AlarmManager重復(fù)監(jiān)聽圃庭,API大于21我們使用JobScheduler監(jiān)聽锄奢,然而JobScheduler在API大于24時(shí)Doze模式會(huì)因?yàn)殡姵貎?yōu)化而無法正常執(zhí)行失晴,我們需要忽略電池優(yōu)化
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
//守護(hù)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秒運(yùn)行一次
//Android 7.0+ 增加了一項(xiàng)針對(duì) 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í)行任務(wù)
builder.setRequiresDeviceIdle(true);
if (jobScheduler.schedule(builder.build()) <= 0) {
Log.w("init", "jobScheduler.schedule something goes wrong");
}
} else {
//發(fā)送喚醒廣播來促使掛掉的UI進(jìn)程重新啟動(dòng)起來
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進(jìn)程拉活涂屁,我們采用開源的守護(hù)進(jìn)程庫。Android-AppDaemon堪滨。該方案主要適用于 Android5.0 以下版本手機(jī)胯陋。該方案不受 forcestop 影響蕊温,被強(qiáng)制停止的應(yīng)用依然可以被拉活袱箱,在 Android5.0 以下版本拉活效果非常好。對(duì)于 Android5.0 以上手機(jī)义矛,系統(tǒng)雖然會(huì)將native進(jìn)程內(nèi)的所有進(jìn)程都?xì)⑺婪⒈剩@里其實(shí)就是系統(tǒng)“依次”殺死進(jìn)程時(shí)間與拉活邏輯執(zhí)行時(shí)間賽跑的問題,如果可以跑的比系統(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í)行定時(shí)任務(wù)無需處于運(yùn)行中,但是手機(jī)重啟后會(huì)清除所有Alarm制轰,所以最終導(dǎo)向還是應(yīng)用鼻凹疲活。
非原生Android系統(tǒng)會(huì)對(duì)系統(tǒng)修改我們需要各種方式配合垃杖,保證最大幾率蹦需荆活。一Notification 提升權(quán)限调俘,二監(jiān)聽解鎖監(jiān)控電池電量和充電狀態(tài)伶棒,開機(jī)廣播,網(wǎng)絡(luò)變化彩库,應(yīng)用安裝肤无、卸載,三守護(hù)GuardService監(jiān)聽骇钦,四利用Native進(jìn)程拉活宛渐。然而這四中方式都無法保證百分百保活眯搭,我們還需要根據(jù)各機(jī)型適配皇忿,引導(dǎo)用戶加入手機(jī)白名單,每個(gè)手機(jī)廠商各個(gè)版本白名單方式都會(huì)變化坦仍,適配路漫漫其修遠(yuǎn)兮鳍烁,只能祈禱國內(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"));
//小米 自啟動(dòng)管理
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 自啟動(dòng)應(yīng)用程序管理
Intent samsungLIntent = context.getPackageManager().getLaunchIntentForPackage("com.samsung.android.sm");
//三星 6.0+ 未監(jiān)視的應(yīng)用程序管理
Intent samsungMIntent = new Intent();
samsungMIntent.setComponent(new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.battery.BatteryActivity"));
//魅族 自啟動(dòng)管理
Intent meizuIntent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
meizuIntent.addCategory(Intent.CATEGORY_DEFAULT);
meizuIntent.putExtra("packageName", context.getPackageName());
//魅族 待機(jī)耗電管理
Intent meizuGodIntent = new Intent();
meizuGodIntent.setComponent(new ComponentName("com.meizu.safe", "com.meizu.safe.powerui.PowerAppPermissionActivity"));
//Oppo 自啟動(dòng)管理
Intent oppoIntent = new Intent();
oppoIntent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
//Oppo 自啟動(dòng)管理(舊版本系統(tǒng))
Intent oppoOldIntent = new Intent();
oppoOldIntent.setComponent(new ComponentName("com.color.safecenter", "com.color.safecenter.permission.startup.StartupAppListActivity"));
//Vivo 后臺(tái)高耗電
Intent vivoGodIntent = new Intent();
vivoGodIntent.setComponent(new ComponentName("com.vivo.abe", "com.vivo.applicationbehaviorengine.ui.ExcessivePowerManagerActivity"));
//金立 應(yīng)用自啟
Intent gioneeIntent = new Intent();
gioneeIntent.setComponent(new ComponentName("com.gionee.softmanager", "com.gionee.softmanager.MainActivity"));
//樂視 自啟動(dòng)管理
Intent letvIntent = new Intent();
letvIntent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
//樂視 應(yīng)用保護(hù)
Intent letvGodIntent = new Intent();
letvGodIntent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.BackgroundAppManageActivity"));
//酷派 自啟動(dòng)管理
Intent coolpadIntent = new Intent();
coolpadIntent.setComponent(new ComponentName("com.yulong.android.security", "com.yulong.android.seccenter.tabbarmain"));
//聯(lián)想 后臺(tái)管理
Intent lenovoIntent = new Intent();
lenovoIntent.setComponent(new ComponentName("com.lenovo.security", "com.lenovo.security.purebackground.PureBackgroundActivity"));
//聯(lián)想 后臺(tái)耗電優(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"));
//中興 鎖屏加速受保護(hù)應(yīng)用
Intent zteGodIntent = new Intent();
zteGodIntent.setComponent(new ComponentName("com.zte.heartyservice", "com.zte.heartyservice.setting.ClearAppSettingsActivity"));
//錘子 自啟動(dòng)權(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"));
- TamingTask后臺(tái)定時(shí)任務(wù)
- 感謝Android鬧鐘設(shè)置的解決方案,Android進(jìn)程狈痹活招式大全幔荒。