我需要将活动实例传递给停止AlarmManager的调用方法。
MainActivity
private void setAlarm(long timeInMilis) {
alarmManager = (AlarmManager) getSystemService((Context.ALARM_SERVICE));
MyAlarm myAlarm = new MyAlarm(this);
Intent intent = new Intent(this, myAlarm.getClass());
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC, timeInMilis, 10000, pendingIntent);
if (dbHelper.getProfile().getHp() >= 100) {
stopAlarmManager();
Toast.makeText(this, "Your character is fully healed.", Toast.LENGTH_LONG).show();
}
}
public void stopAlarmManager() {
if (alarmManager != null)
alarmManager.cancel(pendingIntent);
}
和我的BroadcastReceiver
public class MyAlarm extends BroadcastReceiver {
MainActivity mainActivity;
public MyAlarm() {
}
public MyAlarm(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
@Override
public void onReceive(Context context, Intent intent) {
DBHelper dbHelper = new DBHelper(context);
dbHelper.getWritableDatabase();
dbHelper.setHp("1", dbHelper.getProfile().getHp() + 40);
String currentHp = String.valueOf(dbHelper.getProfile().getHp());
if (Integer.parseInt(currentHp) < dbHelper.getProfile().getHpMax())
Toast.makeText(context, "Your character gain 40HP and now has: " + currentHp + "HP", Toast.LENGTH_LONG).show();
else {
Toast.makeText(context, "Your character is fully healed", Toast.LENGTH_LONG).show();
mainActivity.stopAlarmManager();
}
}
}
但是这段代码会导致错误:原因:java.lang.InstantiationException:空对象引用上的java.lang.Class <(...)MainActivity.stopAlarmManager>