鬧鐘學習

來源:互聯網
上載者:User

最近看了一下Android的鬧鐘管理類(AlarmManager),真不錯誤,強大又簡單,代碼如下:

1、建立一個AlarmReceiver繼承入BroadcastReceiver,並在AndroidManifest.xml聲明
public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "鬧鐘提示:時間到!", Toast.LENGTH_LONG).show();
}
}

2、建立Intent和PendingIntent,來調用目標組件。
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

3、設定鬧鐘
擷取鬧鐘管理的執行個體:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

設定單次鬧鐘:
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5*1000), pendingIntent);

設定周期鬧鐘:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10*1000), (24*60*60*1000), pendingIntent);

 

3--4:

   重開機後重新計算並設定鬧鈴時間

   當然要有一個BootReceiver:
   public class BootReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            //重新計算鬧鈴時間,並調第一步的方法設定鬧鈴時間及鬧鈴間隔時間
          AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

 
          Intent intent = new Intent("Intent.ACTION_REQUEST_SHUTDOWN");

           PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

           int interval = 60 * 1000;//鬧鈴間隔, 這裡設為1分鐘鬧一次,在第2步我們將每隔1分鐘收到一次廣播

            am.set(AlarmManager.RTC_WAKEUP, timeInMillis, interval, sender)

        }
    }
 }
    當然,也需要註冊:
        <receiver android:name="BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.