0

I'm passing an Int to a BroadcastReceiver, but I'm not sure if I'm doing correctly since sometimes it works and sometimes it doesn't.

Sending the Int:

    Intent intent = new Intent(getActivity(),Broadcast_RemoveClass.class);
    Bundle bundle = new Bundle();
    bundle.putDouble("mInt", i);
    intent.putExtras(bundle);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 5, pendingIntent);
    Toast.makeText(getActivity(), "countdown started for: " + i,Toast.LENGTH_LONG).show();

Getting the Int:

public class Broadcast_RemoveClass extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        int i = bundle.getInt("mInt");
        Toast.makeText(context, "done" + i , Toast.LENGTH_LONG).show();
    }
}

Sometimes it gets the current int but then it just comes to a point that it just keeps getting the previous passed int. When sending the intent it shows the correct int in the toast, but then it gets a wrong int in the BroadcastReceiver. Any ideas of what is making this happen?

John Sardinha
  • 3,566
  • 6
  • 25
  • 55
  • Possible duplicate of [android pending intent notification problem](http://stackoverflow.com/questions/3009059/android-pending-intent-notification-problem) – Mike M. May 28 '16 at 21:44

1 Answers1

0

I solved it by instead of passing data through a bundle, I just put the data in a SharedPrefs key and then get that key in the BroadcastReceiver

send:

prefs = getActivity().getSharedPreferences("info", Context.MODE_PRIVATE);
prefs.edit().putInt("mInt", i).apply();

get it:

    SharedPreferences prefs = context.getSharedPreferences("info", Context.MODE_PRIVATE);
    int i = prefs.getInt("i",0);

I hope this helps anyone

John Sardinha
  • 3,566
  • 6
  • 25
  • 55