问题
Broadcast receiver
mBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.i(TAG,"contact list populate broadcast")
var action = intent.action
Log.v("Action is ",action)
when (action) {
GetContactListFromServer -> {
println("Get contact list")
}
}
}
}
val filter = IntentFilter(GetContactListFromServer)
this.registerReceiver(mBroadcastReceiver, filter)
This is how I am sending broadcast
val i = Intent(ContactListActivity.Obz.GetContactListFromServer)
i.`package` = mApplicationContext?.getPackageName()
mApplicationContext?.sendBroadcast(i)
This code is working fine till last night. I am not able to debug what is going wrong?
回答1:
Try Like this
In your activity Inside onCreate method declare
LocalBroadcastManager.getInstance(context).registerReceiver(MyBroadcastReceiver, new IntentFilter("MyFilter"));
Then implement the MyBroadcastReceiver in Activity
private final BroadcastReceiver MyBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String Action = intent.getStringExtra("Action");
switch (Action){
case "updatedata":
String message = intent.getStringExtra("message");
String date_time = intent.getStringExtra("date_time");
break;
default:
break;
}
}
};
Send the Broadcast like this
Intent intent = new Intent("MyFilter");
intent.putExtra("message", message);
intent.putExtra("date_time", date_time);
intent.putExtra("Action", "updatedata");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
来源:https://stackoverflow.com/questions/43489963/broadcast-receiver-onreceive-is-not-called