Subclassing Intent不发送额外内容

时间:2017-06-13 12:59:52

标签: android android-intent extras

为什么这样做:

    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);
  }
}

额外内容未添加到intent中,并且在BroadcastReceiver中接收时为null?

2 个答案:

答案 0 :(得分: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:自定义值

答案 1 :(得分:0)

  

额外内容未添加到意图

您的孩子班必须实施Parcelable