广播收到两次 [英] Broadcast received twice

查看:68
本文介绍了广播收到两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用本地广播让我的服务知道 AsyncTask 已完成其工作,但我有一个小问题:广播仅发送一次(它由仅在应用程序启动时调用的函数创建) 但我收到了两次.

I am using a local broadcast to let my service know that the AsyncTask has finished its work but I have a small issue : the broadcast is only sent once (it is created by a function that is only called when the app is launched) but I receive it twice.

简化代码:

@Override
protected void onPostExecute(HttpResponse result) {
    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getBaseContext());
    localBroadcastManager.sendBroadcast(new Intent(getString(R.string.bc_CONNECTED)));
}

在服务中:

private BroadcastReceiver connectedBroadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(getString(R.string.app_tag), "broadcast received !!");
    }
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    LocalBroadcastManager.getInstance(this).registerReceiver(connectedBroadcastReceiver, new IntentFilter(getString(R.string.bc_CONNECTED)));
    return START_STICKY;
}

有没有人遇到过这种奇怪的行为?

Has anyone encountered such a weird behavior yet?

推荐答案

在响应广播之前,您应该始终检查 Intent Action.

You should always check for the intent Action before responding to the broadcast.

public void onReceive(Context context, Intent intent){
      if(intent.getAction() != null && intent.getAction().equals(getString(R.string.bc_CONNECTED))){
      Log.d(getString(R.string.app_tag), "broadcast received !!");
 }
}

检查 文档.它说您可能会收到虚假电话.所以总是检查动作

Check the documentation. It says you may receive spurious calls. So always check for action

registerReceiver(BroadcastReceiver,IntentFilter) 和在应用程序清单中不能保证独家的.它们是操作系统关于如何查找的提示合适的收件人.发件人可以强制递送至特定收件人,绕过过滤器解析.为此原因,onReceive() 实现应该只响应已知的动作,忽略他们可能收到的任何意外 Intent.

The Intent filters used in registerReceiver(BroadcastReceiver, IntentFilter) and in application manifests are not guaranteed to be exclusive. They are hints to the operating system about how to find suitable recipients. It is possible for senders to force delivery to specific recipients, bypassing filter resolution. For this reason, onReceive() implementations should respond only to known actions, ignoring any unexpected Intents that they may receive.

这篇关于广播收到两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆