我试图在某个时间发出警报,以显示我制作的 Parcelable Java Object
的字段。我知道以前曾有过与此相关的问题,但是,我还没有找到解决该问题的方法。如果没有数据传递给接收器,接收器将成功发出警报,但是,我通过来自 Fragment
的 Intent
发送给它的任何数据创建 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());
}
}
为Receiver
提供Intent
的代码如下:
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);
}
});
最佳答案
使用最新版本的 Android,您无法可靠地放置自定义 Parcelable
或Serializable
Intent
中的对象被传递到 AlarmManager
。您需要将自定义对象序列化为 byte[]
并输入 byte[]
进入Intent
。在 onReceive()
您需要从 byte[]
构造对象再次。
参见How to marshall and unmarshall a Parcelable to a byte array with help of Parcel?或https://gist.github.com/jacklt/6711967代码示例。
关于android - 数据未发送到broadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593376/