我制作了一个闹钟,它的工作效果非常好。 我的问题是报警管理器没有停止。
我有一个切换按钮来设置闹钟但是当我按下关闭状态时,闹钟管理器不会停止播放铃声。
这是我的代码:
public void OnToggleClicked(View view){
long time;
if (((ToggleButton) view).isChecked()){
Toast.makeText(activity_mainnew.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
time = (calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));
if(System.currentTimeMillis()>time){
if (calendar.AM_PM == 0)
time = time + (1000*60*60*12);
else
time = time + (1000*60*60*24);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Toast.makeText(activity_mainnew.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
我的AlarmReceiver课程我有:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
答案 0 :(得分:0)
您没有初始化pendingIntent,
...else
{ Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}....