我在这里有一个问题。我想设置一个警报,然后在10秒后自动将其停止。我使用了下面的代码,但是10秒钟后它并没有停止。
这是我的活动的setAlarm方法:
public void setAlarm(int hour, int minute) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at "hour"
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
Intent i = new Intent(AccueilPA.this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(AccueilPA.this, 10, i, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
test = true;
}
}.start();
// If the alarm has been set, cancel it.
if (alarmManager != null && test) {
alarmManager.cancel(pendingIntent);
}
}
答案 0 :(得分:0)
需要完全像启动AlarmManager时那样创建PendingIntent。 创建时,您已将待处理的意图请求代码设置为10。您必须使用相同的取消它。
创建警报:
private void createalarm(int hour , int minute){
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
Log.i("TestAlarm" , " Created Alarm");
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
cancelAlarm();
}
}.start();
}
取消警报:
private void cancelAlarm(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
Log.i("TestAlarm" , " Cancelled Alarm");
}
BroadCast接收器类别:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("TestAlarm" , "Alarm Triggered!");
}
}