在服務的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); } }
AlarmManager的經常使用方法有三個:.net
type表示鬧鐘類型,startTime表示鬧鐘第一次執行時間,long intervalTime表示間隔時間,PendingIntent表示鬧鐘響應動做code
對以上各個參數的詳細解釋
鬧鐘的類型:blog
絕對時間:1970 年 1月 1 日 0 點get
startTime:
鬧鐘的第一次執行時間,以毫秒爲單位,通常使用當前時間。io
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); } }
運行結果: