日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Android 鬧鐘機制實現(xiàn)定時任務

 勤奮不止 2013-08-06

導讀:Android的鬧鐘實現(xiàn)機制很簡單, 只需要調用AlarmManager.set()將鬧鈴時間記錄到系統(tǒng)中,當鬧鈴時間到后,系統(tǒng)會給應用程序發(fā)送廣播,我們只需要去注冊廣播接收器就可以了。

本文分三部分講解如何實現(xiàn)鬧鐘:

目錄:
1. 設置鬧鈴時間;
2. 接收鬧鈴事件廣播;
3. 重開機后重新計算并設置鬧鈴時間;

正文:
1. 設置鬧鈴時間(毫秒)
 

1private void setAlarmTime(Context context,  long timeInMillis) {
2        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
3        Intent intent = new Intent(”android.alarm.demo.action“);
4        PendingIntent sender = PendingIntent.getBroadcast(
5                context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
6        int interval = 60 * 1000;//鬧鈴間隔, 這里設為1分鐘鬧一次,在第2步我們將每隔1分鐘收到一次廣播
7        am.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, interval, sender)
8    }
2. 接收鬧鈴事件廣播
1public class AlarmReceiver extends BroadcastReceiver {
2    public void onReceive(Context context, Intent intent) {
3        if (”android.alarm.demo.action“.equals(intent.getAction())) {
4            //第1步中設置的鬧鈴時間到,這里可以彈出鬧鈴提示并播放響鈴
5            //可以繼續(xù)設置下一次鬧鈴時間;
6            return;
7        }
8    }
9}
當然,Receiver是需要在Manifest.xml中注冊的:
1<receiver android:name="AlarmReceiver">
2            <intent-filter>
3                <action android:name="android.alarm.demo.action" />
4            </intent-filter>
5        </receiver>
  3. 重開機后重新計算并設置鬧鈴時間 當然要有一個BootReceiver:
1public class BootReceiver extends BroadcastReceiver {
2    public void onReceive(Context context, Intent intent) {
3        String action = intent.getAction();
4        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
5            //重新計算鬧鈴時間,并調第一步的方法設置鬧鈴時間及鬧鈴間隔時間
6        }
7    }
8}
當然,也需要注冊:
1<receiver android:name="BootReceiver">
2            <intent-filter>
3                <action android:name="android.intent.action.BOOT_COMPLETED" />
4            </intent-filter>
5        </receiver>

 

鬧鐘實現(xiàn)原理其實就這么多,至于具體的細節(jié)比如鬧鈴時間存儲及計算, 界面顯示及鬧鈴提示方式,每個人的想法做法都會不一樣,就不贅述。

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多