[英]BroadcastReceiver's onReceive method is not called
I have an Activity with Fragment inside and IntentService. 我有一个带有Fragment和IntentService的Activity。 When I click button dialog fragment opens and I enter my data.
当我单击按钮时,对话框片段打开,然后输入数据。 After that I click Ok and it calls getActivity().startService(intent).
之后,单击确定,它将调用getActivity()。startService(intent)。 Service calls sendBroadcast(intent) through LocalBroadcastManager, but onReceive() method is not being called.
服务通过LocalBroadcastManager调用sendBroadcast(intent),但未调用onReceive()方法。 What's wrong?
怎么了? There's my BroadcastReceiver
有我的广播接收器
private BroadcastReceiver mApiBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("tag", intent.getAction());
switch (intent.getAction()) {
case "register":
showMessage(intent.getStringExtra(ApiService.EXTRA_ANSWER));
break;
case "authorize":
showProfile((User) intent.getParcelableExtra(ApiService.EXTRA_USER));
break;
default:
break;
}
}
};
I register receiver here 我在这里注册接收者
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.
getInstance(this).
registerReceiver(mApiBroadcastReceiver, new IntentFilter(ApiService.API_BROADCAST));
}
my onDestroy method 我的onDestroy方法
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mApiBroadcastReceiver);
}
and my method in service which sends broadcast 和我在服务中发送广播的方法
private void sendMessage(Object answer) {
Intent intent = new Intent(API_BROADCAST);
if (answer instanceof String) {
intent.setAction("register");
Log.d("tag", answer.toString());
intent.putExtra(EXTRA_ANSWER, answer.toString());
} else if (answer instanceof User) {
intent.setAction("authorize");
intent.putExtra(EXTRA_USER, (User) answer);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You should not call intent.setAction()
. 您不应调用
intent.setAction()
。
You are listening for Intents with action ApiService.API_BROADCAST
: 您正在使用
ApiService.API_BROADCAST
操作监听Intent:
new IntentFilter(ApiService.API_BROADCAST)
; new IntentFilter(ApiService.API_BROADCAST)
; new Intent(ApiService.API_BROADCAST)
; new Intent(ApiService.API_BROADCAST)
; That is OK, but if you later call intent.setAction("register")
, you are overriding the first action you set. 可以,但是如果以后调用
intent.setAction("register")
,则将覆盖您设置的第一个操作。
Instead, try passing the sub-action string as an Extra
: 相反,尝试将子操作字符串作为
Extra
传递:
private void sendMessage(Object answer) {
Intent intent = new Intent(API_BROADCAST);
if (answer instanceof String) {
intent.putExtra(EXTRA_WHAT, "register");
intent.putExtra(EXTRA_ANSWER, answer.toString());
} else if (answer instanceof User) {
intent.putExtra(EXTRA_WHAT, "authorize");
intent.putExtra(EXTRA_USER, (User) answer);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.