Search code examples
androidbroadcastreceiverandroid-broadcast

BroadcastReceiver loses data after reboot


data seems to get lost after I reboot my device or even close my app, I pass data to the BroadCastReceiver with an intent.

How I set my alarms, the user gets prompted with a DatePicker dialog

public void setAlarm(View view) {

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, yearDate);
    cal.set(Calendar.MONTH, monthDate);
    cal.set(Calendar.DAY_OF_MONTH, dayDate);
    long alertTime = cal.getTimeInMillis();

    Intent alertIntent = new Intent(this, AlertReceiver.class);

    alertIntent.putExtra("name", name);
    alertIntent.putExtra("id", mainId);
    alertIntent.putExtra("releaseDate", releaseDate);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime,
            PendingIntent.getBroadcast(this, mainId, alertIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));

}

Broadcastreceiver onReceive()

public class AlertReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    String name = intent.getStringExtra("name");
    String releaseDate = intent.getStringExtra("releaseDate");
    int id = intent.getIntExtra("id", 0);

    createNotification(context, name + "releases on" + releaseDate, "Reminder", id);

  }
}

After I reboot my device or even close my app, the Broadcast loses its data? Instead of getting; Movie releases on 07/11/2015, I get null releases on null. The intents get deleted? (Don't know the proper term). Instead of showing a message like "THIS movie is out" , it shows instead "null is out", and it only shows one notification, no more than one, so BroadcastReceiver only reminds me about the last movie I last set a reminder to, thanks!

My Android manifest:

<receiver android:name=".AlertReceiver"
              android:enabled="true">
        <intent-filter android:priority="100">
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

Solution

  • Yes, your app's in-memory state is lost when your process dies (which it can do at pretty much any time your app is not in the foreground). This is not unique to Android.

    If you want to keep your data, you have to store it to disk in some way. You should read the official guide on storage in Android: http://developer.android.com/guide/topics/data/data-storage.html