Android開發 定時任務清理數據

原文地址:Android開發 定時任務清理數據 | Stars-One的雜貨小窩

公司項目,需要整定時任務,對數據進行清理,需要在每天凌晨0:00進行數據的清理,使用了Alarm和廣播的方式來實現

PS:基於此原理,也可以實現自動檢測並更新apk的功能

實現

實現的原理爲:
1.進入APP,啓動鬧鐘,設置一個鬧鐘服務(在某個時間點會觸發任務),任務中其實主要是發出一個廣播

2.設置廣播接收器裏的邏輯,其中包含清理數據和重新設置鬧鐘服務(即上述第一步)

之後即可一直循環,可以保證穩定執行

鬧鐘

設置一個鬧鐘服務,指定第二天的凌晨0:00:00開始觸發任務

//構造一個PendingIntent對象(用於發送廣播)
//注:ALARM_ACTION_CODE這個是action,後面需要匹配判斷
String ALARM_ACTION_CODE = "ALARM_ACTION_CODE";
Intent intent = new Intent(ALARM_ACTION_CODE);
//適配8.0以上(不然沒法發出廣播)
if (DeviceUtils.getSDKVersionCode() > Build.VERSION_CODES.O) {
    intent.setComponent(new ComponentName(this, DataDeleteReceiver.class));
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
        1, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);

//在第二天的0:00清理髮出清理數據的廣播
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DAY_OF_MONTH, 1);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

KLog.d("鬧鐘已啓動,預定觸發時間:" + TimeUtils.date2String(calendar.getTime()));

廣播接收邏輯

直接通過Android Studio的菜單直接新建一個廣播

enabledexported都勾選即可

當時間到點後,系統會發送一個廣播,我們程序需要去接收此問題

public class DataDeleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //匹配下之前定義的action
        if ("ALARM_ACTION_CODE".equals(action)) {
            KLog.d("-----定時清理數據-----");
            //刪除數據(需要開個子線程去操作)
            
            
            //這裏重新設置定時器
            
            //方便起見,這裏我是跳轉回MainActivity去重新執行了
            EventBus.getDefault().post(new AlarmEvent());
           
        }
    }
}

補充——定時任務的8種方式

Java SDK:

  • while循環+sleep
  • 遞歸+sleep
  • Timer、TimerTask
  • ScheduledExecutorService(帶有定時任務的線程池)

Android SDK:

  • Handler循環發消息
  • Handler的postDelayed方法
  • BroadcastReceiver循環自發廣播
  • AlarmManger+BroadcastReceiver定時發送廣播

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章