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);
4.取消闹钟
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//只有设置相同的Intent才会取消该闹钟
alarmManager.cancel(pendingIntent);
ps:闹钟管理时,有需求用多个闹钟,AlarmManager是如果设置相同的Intent,将视为替代之前设置的闹钟,即使设置的是不同的闹铃时间。