Android長時間定時任務實現


在服務的onStartCommand方法里面使用AlarmManager 定時喚醒發送廣播,在廣播里面啟動服務

  每次執行startService方法啟動服務都會執行onStartCommand

1、服務定時喚醒  60秒發一次廣播

public class MediaService extends Service {
    public MediaService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /*每次調用startService啟動該服務都會執行*/
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("TAG", "啟動服務:" + new Date().toString());

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

        long triggerTime = SystemClock.elapsedRealtime() + 60000;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

}

采用AlarmManger實現長期精確的定時任務

AlarmManager的常用方法有三個:

  • set(int type,long startTime,PendingIntent pi);//一次性
  • setExact(int type, long triggerAtMillis, PendingIntent operation)//一次性的精確版
  • setRepeating(int type,long startTime,long intervalTime,PendingIntent 
    pi);//精確重復
  • setInexactRepeating(int type,long startTime,long 
    intervalTime,PendingIntent pi);//非精確,降低功耗

type表示鬧鍾類型,startTime表示鬧鍾第一次執行時間,long intervalTime表示間隔時間,PendingIntent表示鬧鍾響應動作


對以上各個參數的詳細解釋 
鬧鍾的類型:

  • AlarmManager.ELAPSED_REALTIME:休眠后停止,相對開機時間
  • AlarmManager.ELAPSED_REALTIME_WAKEUP:休眠狀態仍可喚醒cpu繼續工作,相對開機時間
  • AlarmManager.RTC:同1,但時間相對於絕對時間
  • AlarmManager.RTC_WAKEUP:同2,但時間相對於絕對時間
  • AlarmManager.POWER_OFF_WAKEUP:關機后依舊可用,相對於絕對時間

絕對時間:1970 年 1月 1 日 0 點

startTime: 
鬧鍾的第一次執行時間,以毫秒為單位,一般使用當前時間。

  • SystemClock.elapsedRealtime():系統開機至今所經歷時間的毫秒數
  • System.currentTimeMillis():1970 年 1 月 1 日 0 點至今所經歷時間的毫秒數

intervalTime:執行時間間隔。

PendingIntent : 
PendingIntent用於描述Intent及其最終的行為.,這里用於獲取定時任務的執行動作。 
詳細參考譯文:PendingIntent

 

 

2、接收到廣播調用startService啟動服務

  

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MediaService.class);
        context.startService(i);
    }
}

運行結果:

                       

 


免責聲明!

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



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