将activity_main.xml中的onClick绑定到setAlarm为一个按钮并将unsetAlarm绑定到同一活动中的另一个按钮时,单击链接到unsetAlarm方法的按钮时,以下代码将不允许您取消设置警报。
...package name and includes ommitted...
public class MainActivity extends Activity {
private AlarmManager alarmManager;
private PendingIntent notifyIntent;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void setAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Log.v(TAG, "time for alarm trigger:" + calendar.getTime().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, notifyIntent);
}
public void unsetAlarm(View v) {
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}
}
解决方法是(正如我在Notifications and AlarmManager - cancelling the alarm I set中提供的那样)在unsetAlarm方法中重新创建pendingIntent:
public void unsetAlarm(View v) {
Intent myIntent = new Intent(MainActivity.this,
NotificationService.class);
notifyIntent = PendingIntent.getService(MainActivity.this, 0,
myIntent, 0); // recreate it here before calling cancel
alarmManager.cancel(notifyIntent);
Log.v(TAG, "cancelling notification");
}
我的问题是:为什么我不能重复使用PendingIntent,存储在第一个代码片段中的“notifyIntent”字段中?为什么我必须重新创建它才能取消它?我已经将MainActivity设置为具有属性 android:launchMode =“singleInstance”所以当我点击NotificationService中创建的通知时我应该相信它使用相同的实例(我已经省略了它但是它只是显示通知)。