数据未发送到broadcastReceiver

时间:2016-11-14 16:24:58

标签: android broadcastreceiver

我正在尝试在某个时间发出提醒,以显示我制作的Parcelable Java Object字段。我知道之前有过与此有关的问题,但是,我还没有找到解决这个问题的办法。如果没有数据传递给ReceiverIntent会成功发出警报,但是,我通过创建Fragment的{​​{1}} Receiver发送给它的任何数据都是不保持。

Receiver的代码如下:

public class NotificationReceiver extends BroadcastReceiver {

@Override
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));
    repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent)
            .setSmallIcon(android.R.drawable.arrow_up_float)
            .setContentTitle("Warning: Approaching Threshold")
            .setContentText(eu.get_forecast_info().get_estimate_cur_cycle_total_cost()+" is the price")
            .setAutoCancel(true);

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

Intent提供Receiver的代码如下:

trigger_b = (Button) view.findViewById(R.id.trigger_button);
    trigger_b.setOnClickListener(new View.OnClickListener() {
        @Override
        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);
            intent.putExtras(c);
            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);
        }
    });

1 个答案:

答案 0 :(得分:1)

使用最新版本的Android,您无法在传递给Parcelable的{​​{1}}中可靠地放置自定义SerializableIntent对象。您需要将自定义对象序列化为AlarmManager并将byte[]放入byte[]。在Intent中,您需要再次从onReceive()构建对象。

有关代码示例,请参阅How to marshall and unmarshall a Parcelable to a byte array with help of Parcel?https://gist.github.com/jacklt/6711967