最近看了一下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>