2017-06-13 99 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,它也可以工作。 –