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定時發送廣播

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM