我有一个像这样的Serializable:
public class Main implements Serializable {
private static final long serialVersionUID = 5053412967314724078L;
private ArrayList<Carte> main = new ArrayList<Carte>();
public Main() {}
public Main(Carte[] cartes) {
for (Carte carte:cartes) {
this.main.add(carte);
}
}
public Carte[] getMain() {
return (Carte[]) main.toArray();
}
public String toString() {
String result = "";
for (Carte carte : main) {
result += carte.toString() + " ";
}
return result;
}
}
我将序列化作为额外的意图发送:
Carte[] cards = ...// Which is initialized elsewhere and been checked, there's no problem with that.
Main mainSerial = new Main(cards);
Intent broadcast = new Intent();
broadcast.setAction("coinchutc.RECUP");
broadcast.putExtra("cards", mainSerial);
Log.d("JoueurAgent", "Sending broadcast " + broadcast.getAction() + " " + mainSerial.toString());
context.sendBroadcast(broadcast);
在日志中我可以正确打印调试消息,也就是说我已经成功构建了可序列化的文件。
然后我尝试接受意图,但没有成功:
在我完成的目标Activity的onCreate()中:
IntentFilter recupFilter = new IntentFilter();
recupFilter.addAction("coinchutc.RECUP");
registerReceiver(myReceiver, recupFilter);
我创建了BroadcastReceiver类来接收广播:
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("RejoindrePartieActivity", "receive");
String action = intent.getAction();
Log.d("RejoindrePartieActivity", "Receive action " + action);
if (action.equalsIgnoreCase("coinchutc.RECUP")) {
Log.d("RejoindrePartieActivity", "RECUP");
Bundle extras = intent.getExtras();
if (extras != null) {
Main main = (Main) extras.getSerializable("cards");
//String recup = extras.getString("cards");
Log.d("RejoindrePartieActivity", "Receive " + main.toString());
}
}
}
但它什么也没收到。即使是第一个日志也不会被打印出来。
然后我将serializable改为一个简单的字符串。这一切都奏效了! 所以我想知道我是否具有序列化权限,为什么intentfilter甚至无法接收到意图。
提前致谢!
答案 0 :(得分:1)
IntentFilter recupFilter = new IntentFilter();
recupFilter.addAction("coinchutc.RECUP");
registerReceiver(myReceiver, recupFilter);
以上代码必须在sendBroadcast()
之前调用。在发送Intent之前调用它。
经过SO-
的澄清Carte class also needs to be `Serializable` and this does work.