Android長時間定時任務實現

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

  每次執行startService方法啓動服務都會執行onStartCommandthis

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

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的經常使用方法有三個:.net

  • 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表示鬧鐘響應動做code


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

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

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

startTime: 
鬧鐘的第一次執行時間,以毫秒爲單位,通常使用當前時間。io

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

intervalTime:執行時間間隔。ast

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

 

 

二、接收到廣播調用startService啓動服務

  

public class AlarmReceiver extends BroadcastReceiver {

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

運行結果:

                       

相關文章
相關標籤/搜索