我有一个内部有 Fragment 和 IntentService 的 Activity。当我单击按钮对话框片段打开并输入我的数据。之后,我单击 Ok 并调用 getActivity().startService(intent)。服务通过 LocalBroadcastManager 调用 sendBroadcast(intent),但未调用 onReceive() 方法。怎么了?有我的广播接收器
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;
}
}
};
我在这里注册接收器
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.
getInstance(this).
registerReceiver(mApiBroadcastReceiver, new IntentFilter(ApiService.API_BROADCAST));
}
我的 onDestroy 方法
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mApiBroadcastReceiver);
}
和我在服务中发送广播的方法
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);
}