我剛剛熟悉本地廣播消息。我有2個活動。我的活動未收到其他活動發送的本地廣播
MainActivity:
我有2個按鈕。點擊1按鈕,我正在廣播消息。點擊另一個,我正在導航到第二個活動。
public class MainActivity extends AppCompatActivity {
Button btn;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.sendBroadCast);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
btn1 = (Button)findViewById(R.id.btn);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
void sendMessage(){
Log.d("RAK","Gonna send braodcast");
Intent intent = new Intent("customMsg");
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
第二活動:
註冊對該活動的onCreate接收機。
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d("RAK","In oncreate of second activity.Registered for local receiver");
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("customMsg"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
我面臨的問題是,第二個Activity沒有收到廣播。請幫幫我。
P.S:請不要標記爲重複。我按照這個鏈接:how to use LocalBroadcastManager?
感謝, 拉克什
你怎麼樣ry發送消息? 我的意思是, 首先你運行你的應用程序,然後點擊第二個按鈕? – Pein
當你點擊'btn1'然後回去點擊'btn'時會發生什麼? –