James James - 1 year ago 74
Android Question

Data not being sent to broadcastReceiver

I am trying to make an alert at a certain time to display a field of a

Java Object
I made. I know there have been questions pertaining to this before, however, I have not found a solution to this problem. The
will successfully make the alert if no data is passed to it, however, any data I send to it via
from the
that creates the
is not maintained.

My code for the
is below:

public class NotificationReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
IUser eu = intent.getExtras().getParcelable("USER");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(new Intent(context, MainActivity.class));

PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle("Warning: Approaching Threshold")
.setContentText(eu.get_forecast_info().get_estimate_cur_cycle_total_cost()+" is the price")

notificationManager.notify(100, builder.build());

The code for supplying
is below:

trigger_b = (Button) view.findViewById(R.id.trigger_button);
trigger_b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 14);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(getActivity().getApplicationContext(), NotificationReceiver.class);
Bundle c = new Bundle();
c.putParcelable("USER", eu);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

Answer Source

With the latest versions of Android, you cannot reliably put a custom Parcelable or Serializable object in an Intent that is passed to AlarmManager. You will need to serialize the custom object into a byte[] and put the byte[] into the Intent. In onReceive() you will need to construct the object from the byte[] again.

See How to marshall and unmarshall a Parcelable to a byte array with help of Parcel? or https://gist.github.com/jacklt/6711967 for code examples.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download