将activity_main.xml中的onClick绑定到setAlarm到一个按钮,unsetAlarm到同一个activity中的另一个按钮时,下面的代码不会让你在单击链接到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 和 AlarmManager 中提供的 - 取消我设置的警报)在 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");
}
我的问题是:为什么我不能重用存储在第一个代码片段中的“notifyIntent”字段中的 PendingIntent?为什么我必须重新创建它才能取消它?我已将 MainActivity 设置为具有属性android:launchMode="singleInstance"所以我应该相信当我单击在 NotificationService 中创建的通知时它使用的是相同的实例(我已经省略了它,但它只显示了一个通知)。