我有一个public class Alarm implements Serializable
类。其中有一种方法:
public void schedule(Context context) {
setAlarmActive(true);
Intent myIntent = new Intent(context, AlarmAlertBroadcastReciever.class);
Bundle bundle = new Bundle();
bundle.putSerializable("alarm", this);
myIntent.putExtras(bundle);
//myIntent.putExtra("alarm", this);
Alarm alarm = (Alarm) bundle.getSerializable("alarm");
if(alarm !=null){
Log.d("Alarmdebug", "alatm is not null");
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, getAlarmTime().getTimeInMillis(), pendingIntent);
}
在其他地方我有此代码。无法获得serialized
Extras。调用了这一点,但alarm
始终是 null
。
Bundle bundle = intent.getExtras();
final Alarm alarm = (Alarm) bundle.getSerializable("alarm");
if(alarm==null){
Log.d("Alarmdebug", "alarm is null 2");
}
您能告诉我此代码的问题是什么?我在这里尝试了解决方案:使用序列化传递意图,但对我不起作用。
谢谢
编辑
任何寻求解决方案的人现在都可以在下面找到它。
似乎串行捆绑包在某些设备上不起作用。必须到byte[]
答案在这里:
将可序列化对象传递给待处理意图
这样发送:
//AlarmService.java
Intent myIntent = new Intent(getApplicationContext(), AlarmAlertBroadcastReciever.class);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(alarm);
out.flush();
byte[] data = bos.toByteArray();
myIntent.putExtra("alarm", data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm.getAlarmTime().getTimeInMillis(), pendingIntent);
像这样收到它:
//AlarmAlertBroadcastReceiver.java
@Override
public void onReceive(Context context, Intent intent) {
ByteArrayInputStream bis = new ByteArrayInputStream(intent.getByteArrayExtra("alarm"));
ObjectInput in = null;
Alarm alarm = null;
try {
in = new ObjectInputStream(bis);
alarm = (Alarm)in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}