Android廣播的基本使用
阿新 • • 發佈:2018-12-10
這裡我就簡單寫個動態註冊廣播的使用案例
- 傳送方(請求方)
傳送廣播
Intent intent = new Intent();
//設定廣播的名字(設定Action)
intent.setAction("voice_home");
sendBroadcast(intent);
- 接收方
註冊廣播
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction("voice_home");
//註冊廣播
registerReceiver(voiceReceiver, myIntentFilter);
廣播接收
private BroadcastReceiver voiceReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("voice_home")) { Intent intent1 = new Intent(HostMainActivity.this,HostVoiceActivity.class); intent1.putExtra("voice_type","home"); startActivity(intent1); } } };