SendOrderedBroadcast问题:更正的目的是发送一个

时间:2019-07-15 15:54:50

标签: android android-intent broadcastreceiver

当我调用sendOrderedBroadcast方法时,传递给onReceive的Intent与我发送的完全相同。

Intent intent = new Intent(Action.ACTION);
context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent1) {
        String action = intent1.getAction();
        //action is still Action.ACTION
        if(!action.equals(Action.DIFFERENT_ACTION)) {
            return;
        }
        assertEquals(Action.DIFFERENT_ACTION, action);
        Bundle bundle1 = intent1.getExtras();
        assertEquals(bundle1.getString(ExtraConstants.TYPE), ExtraConstants.MONITOR);
    }
}, null, Activity.RESULT_OK, null, null);

甚至返回带有setResult方法的捆绑包都无济于事。 预期的接收者也能够接收该意图并正确使用它,但是我找不到从该接收者进行回复的方法。 有什么想法吗?

EDIT-1

我正在测试使用robolectric动态注册的广播接收器[我们将其称为BR1]。在这段代码中,我向BR1发送了一个意图,我希望BR1设置要由片段中的BroadcastReceiver接收的结果(我们将其称为BR2)。发生的是,发送给BR1的意图也被BR2接收,而不再被调用

EDIT-2 在您找到代码之后,我正在一个独立的Android应用程序中尝试相同的事情

public class MyActivity extends AppCompatActivity {
    @Override
    public void onStart() {
        super.onStart();
        MyReceiver receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("call.br.my");
        this.registerReceiver(receiver, intentFilter);
    }

    public void sendMessage(View view) {
        Intent intent = new Intent("call.br.my");
        intent.putExtra("hello", "ciao");
        sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getStringExtra("hello") != null) {
                    return;
                }
                log.info(intent.getStringExtra("ciao"));
            }
        }, null, Activity.RESULT_OK, null, null);
    }
}

public class MyReceiver extends BroadcastReceiver {

    private static final Logger log = Logger.getLogger(MyReceiver.class.getName());

    @Override
    public void onReceive(Context context, Intent intent) {

        log.info(intent.getStringExtra("hello"));
        Bundle bundle = new Bundle();
        bundle.putString("ciao", "hello1");
        setResult(Activity.RESULT_OK, "ciao", bundle);
    }
}

但是束束中的字符串未被sendOrderedBroadcast中声明的BroadcastReceiver接收,该束只能接收发送的意图。

1 个答案:

答案 0 :(得分:0)

在获得结果的BroadcastReceiver中,您不直接使用intent参数,而是必须调用getResultExtras()

例如在科特林:

<div>
    <p> some text <a href="/map/find_me_1">find_me_1</a></p>
    <br>
    <a href="/map/find_me_2">find_me_2</a>
    <div>
        <div>
            <a href="example.com?page=something&amp;id=55">don't even think about it!</a>
            <a href="/map/find_me_3">find_me_3</a>
        </div>
    </div>
</div>

然后您可以通过resultExtras获得设置的所有捆绑包/额外数据