活动未收到来自服务的本地广播 [英] Local broadcast from Service not received by Activity
问题描述
我有一个Activity
,其中要在本地注册BroadcastReceiver
如下:
I have an Activity
in which I am registering a BroadcastReceiver
locally as follows:
public class SomeActivity extends Activity{
public static final String PERFORM_SOME_ACTION = "PERFORM_SOME_ACTION";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_activity_layout);
.....
.....
IntentFilter filter = new IntentFilter();
filter.addAction(PERFORM_SOME_ACTION);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// perform some action ...
}
};
registerReceiver(receiver, filter);
}
.....
.....
}
我有一个Service
,可以从中广播Intent
,如下所示:
And I have a Service
from which I broadcast an Intent
as follows:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent i = new Intent(SomeActivity.PERFORM_SOME_ACTION);
sendBroadcast(i); /* Send global broadcast. */
return START_STICKY;
}
这按预期工作.实施此方法后,我意识到本地广播将更适合这种情况:
This works as intended. After having implemented this, I realized that a local broadcast would be more appropriate for this situation:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent i = new Intent(SomeActivity.PERFORM_SOME_ACTION);
LocalBroadcastManager.getInstance(this).sendBroadcast(i); /* Send local broadcast. */
return START_STICKY;
}
不幸的是,以上方案不起作用.每次都会发送全球广播,而本地广播显然从不发送/接收.
Unfortunately, the above scheme doesn't work. A global broadcast is sent every time, while a local broadcast is apparently never sent/received.
我在这里想念什么?不能在两个不同的应用程序组件之间(例如两个单独的Activity
或从Service
到Activity
)发送本地广播吗?我在做什么错??
What am I missing here? Can't local broadcasts be sent between two distinct app components, like two separate Activity
s or from a Service
to an Activity
? What am I doing wrong??
注意:
根据文档,效率更高,更重要的是发送本地广播( 应用内 广播,其范围仅限于应用自身的组件)而不是全局广播( 应用间 广播,该广播将传输到电话上的每个单个应用),只要我们不需要该广播将其传播到应用之外即可.这就是做出上述更改的原因.
As per the documentation, it is more efficient and more to the point to send a local broadcast (an intra-app broadcast whose scope is restricted to the app's own components) rather than a global broadcast (an inter-app broadcast which is transmitted to every single app on the phone) whenever we do not need the broadcast to propagate outside the application. This is the reason for making the aforementioned change.
推荐答案
我在这里想念什么?
What am I missing here?
使用LocalBroadcastManager
注册LocalBroadcast,当前使用Activity的registerReceiver
方法注册全局广播:
Use LocalBroadcastManager
for registering LocalBroadcast, currently using registerReceiver
method of Activity which is used for registering global Broadcast:
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
这篇关于活动未收到来自服务的本地广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!