Android 設定鬧鈴步驟和基礎代碼

來源:互聯網
上載者:User

標籤:

主要分三步:1. 設定鬧鈴時間;2. 接收鬧鈴事件廣播;3. 重開機後重新計算並設定鬧鈴時間; 1. 設定鬧鈴時間(毫秒)
private void setAlarmTime(Context context,long timeInMillis) {  AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);  Intent intent = new Intent(”android.alarm.demo.action“);  PendingIntent sender = PendingIntent.getBroadcast(      context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);  int interval = 60 * 1000;//鬧鈴間隔, 這裡設為1分鐘鬧一次,在第2步我們將每隔1分鐘收到一次廣播  am.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, interval, sender)  }

2. 接收鬧鈴事件廣播

public class AlarmReceiver extends BroadcastReceiver {  public void onReceive(Context context, Intent intent) {  if (”android.alarm.demo.action“.equals(intent.getAction())) {    //第1步中設定的鬧鈴時間到,這裡可以彈出鬧鈴提示並播放響鈴    //可以繼續設定下一次鬧鈴時間;    return;  }  }}

當然,Receiver是需要在Manifest.xml中註冊的:

<receiver android:name="AlarmReceiver">    <intent-filter>      <action android:name="android.alarm.demo.action" />    </intent-filter></receiver>

3. 重開機後重新計算並設定鬧鈴時間 當然要有一個BootReceiver:

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

當然,也需要註冊:

<receiver android:name="BootReceiver">    <intent-filter>      <action android:name="android.intent.action.BOOT_COMPLETED" />    </intent-filter></receiver>

鬧鐘實現原理其實就這麼多,至於具體的細節比如鬧鈴時間儲存及計算, 介面顯示及鬧鈴提示方式,每個人的想法做法都會不一樣

Android 設定鬧鈴步驟和基礎代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.