我正在尝试在某个时间发出提醒,以显示我制作的Parcelable Java Object
字段。我知道之前有过与此有关的问题,但是,我还没有找到解决这个问题的办法。如果没有数据传递给Receiver
,Intent
会成功发出警报,但是,我通过创建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);
}
});
答案 0 :(得分:1)
使用最新版本的Android,您无法在传递给Parcelable
的{{1}}中可靠地放置自定义Serializable
或Intent
对象。您需要将自定义对象序列化为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。