我正在参加主要活动。有一个登录按钮 b登录。按下该按钮后,将显示注销按钮 bLogout 。这两个按钮的 onClick 方法如下:
I am in the main activity. There is a Login button bLogin. When it is pressed, a Logout button is displayed bLogout. The onClick methods for the two buttons are as follows:
bLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { llLogin.setVisibility(View.GONE); llLogout.setVisibility(View.VISIBLE); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 327, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); } }); bLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { llLogout.setVisibility(View.GONE); llLogin.setVisibility(View.VISIBLE); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 327, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); manager.cancel(pendingIntent); boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 327, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_NO_CREATE) != null); if(!alarmUp){ Toast.makeText(getBaseContext(), "up", Toast.LENGTH_SHORT).show(); } } });如上面的代码所示,当 bLogin 被按下,我设置了警报,当 bLogout 被按下时,我取消了警报。
As can be seen in the code above, when bLogin is pressed, I set the alarm, and when bLogout is pressed, I cancel the alarm.
alarmUp 用于检查是否设置了警报。但是问题在于,该警报永远不会取消,因为末尾的 Toast 不会显示。另外,在未设置警报时应用程序应完成的工作永远不会按注销来完成。
alarmUp is used to check if the alarm is set. But the problem is that the alarm is never cancelled because the Toast at the end is never displayed. Also, the work that should be done by the app when the alarm is not set is never done on pressing Logout.
我不能似乎弄清楚什么可能是错的。 PendingIntent 在设置闹钟和取消闹钟时都是相同的。
I can't seem to figure out what might be wrong. The PendingIntents are the same for both when the alarm is set, and when it is cancelled.
推荐答案您不会取消 PendingIntent 。致电时
manager.cancel(pendingIntent)您正在取消警报。这不会取消 PendingIntent 。 PendingIntent 仍然存在。因此,当您随后致电
you are cancelling the alarm. This doesn't cancel the PendingIntent. The PendingIntent still exists. So when you then call
boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 327, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_NO_CREATE) != null);PendingIntent 仍然存在,因此 PendingIntent.getBroadcast()将返回非null。结果。 alarmUp 始终为 true 。
the PendingIntent still exists, so PendingIntent.getBroadcast() will return a non-null. result. alarmUp will always be true.
您需要取消闹钟后,取消 PendingIntent ,例如:
You need to cancel the PendingIntent after you cancel the alarm, like this:
pendingIntent.cancel();更多推荐
Android警报未取消
发布评论