在button事件下使用alarmmanager获取Timepicker时间,并到该时间后响铃
时间: 2023-03-25 13:03:23 浏览: 90
可以使用以下代码实现:
1. 在button的点击事件中获取Timepicker的时间:
TimePicker timePicker = findViewById(R.id.timePicker);
int hour = timePicker.getHour();
int minute = timePicker.getMinute();
2. 使用AlarmManager设置定时任务:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, , intent, );
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, );
long triggerTime = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
3. 创建AlarmReceiver类,用于接收定时任务的广播并响铃:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 播放铃声
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
ringtone.play();
}
}
阅读全文