Potrzebuję przekazać Activity żeby wywołać na niej metodę zatrzymującą 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);
}
and my 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();
}
}
}
Ale ten kod powoduje MainActivity.stopAlarmManager()' on a null object reference