2017-06-13 61 views
2

为什么这项工作:子类意向不发送额外

sendBroadcast(MyUtil.configMyIntent(
         new Intent(), 
         ActionType.DATE, 
         new Date().toString())); 

有:

public static Intent configMyIntent(Intent intent, ActionType actionType, String content){ 

     intent.setAction("myCustomBroadcastIntentAction"); 
     intent.putExtra("actionType",actiontype); 
     intent.putExtra("content", content); 
     return intent; 
    } 

但是使用子类时:

CustomIntent intent = new CustomIntent(ActionType.DATE, new Date().toString()); 
sendBroadcast(intent); 

public class CustomIntent extends Intent { 

    public CustomIntent(ActionType actionType, String content) { 
    super(); 
    this.setAction("myCustomBroadcastIntentAction"); 
    this.putExtra("actionType",actionType); 
    this.putExtra("content", content); 
    } 
} 

附加信息不会添加到意图中,并且在BroadcastReceiver中接收时为空?

回答

0

演员不会添加到意图

你的孩子的类必须实现Parcelable

+2

你能解释一下为什么吗? –

1

我还没有确切地指出了你的代码的问题。但是,我想也许ActionType(我认为是一个枚举)是一个需要调查的领域。 ActionType是否需要可序列化?

在任何情况下,此代码适用于我。也许是有用的:

public class MainActivity extends AppCompatActivity { 

    BroadcastReceiver myReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Log.v("MyBroadcastReceiver", "action type:" + intent.getSerializableExtra("actionType") + 
        " myExtra:" + intent.getStringExtra("myExtra")); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("myAction")); 

     Intent standardIntent = new Intent("myAction"); 
     standardIntent.putExtra("actionType", ActionType.DATE); 
     standardIntent.putExtra("myExtra", "standard value"); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(standardIntent); 

     Intent customIntent = new CustomIntent(ActionType.DATE, "custom value"); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(customIntent); 
    } 

    private static class CustomIntent extends Intent { 
     CustomIntent(ActionType actionType, String val) { 
      super(); 
      this.setAction("myAction"); 
      this.putExtra("actionType", actionType); 
      this.putExtra("myExtra", val); 
     } 
    } 

    private enum ActionType implements Serializable { 
     DATE 
    } 

} 

这是日志输出:

V/MyBroadcastReceiver:动作类型:DATE myExtra:标准值

V/MyBroadcastReceiver:动作类型:DATE myExtra:自定义值

+0

嗯,有趣。看来唯一的区别是你的CustomIntent类是静态的。 顺便说一句,没有必要使枚举可串行化,枚举是可序列化的。 –

+0

啊。关于可序列化的好点。我的错。所以这不是问题。 –

+0

如果我让我的CustomIntent类非静态,它仍然适用于我。如果我不使用LocalBroadcastManager,它也可以工作。 –