gpt4 book ai didi

android - 为什么要在 BroadcastReceiver 中调用 setResult?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:09 25 4
gpt4 key购买 nike

在谷歌的 C2DM 示例代码中,当在 BroadcastReceiver 中收到通知时,他们调用:

setResult(Activity.RESULT_OK, null/* data */, null/* extra */);

我不知道 setResult 的作用。这是他们在 Android 文档中所说的:

Change all of the result data returned from this broadcasts; only works with broadcasts sent through Context.sendOrderedBroadcast. All current result data is replaced by the value given to this method.

有人能解释一下他们的意思以及为什么我需要这样调用它吗?

完整代码:

public class C2DMBaseReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
C2DMReceiver.runIntentInService();
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
}

最佳答案

BroadcastReceiver 中的setResult(...) 方法,最重要的是用于跟踪目的。

如果你熟悉Activity的方法setResult(...),你可以用同样的方式来思考广播中的这个方法。但是在 Activity 的情况下,不是像 onActivityResult(int requestCode, int resultCode, Intent data) 这样的回调方法,而是使用广播 setResult(...) 方法来按特定顺序跟踪广播结果,这就是为什么 documentation说:

Only works with broadcasts sent through Context.sendOrderedBroadcast. All current result data is replaced by the value given to this method.

这意味着您可以使用方法 getResultCode()getResultData()getResultExtras() 来了解事情的进展在为处理您的广播而注册的所有不同 BroadcastReceiver 中执行 onReceive(Context, Intent) 方法期间。这样就可以知道在所有receiver上当前执行的代码之前调用的上一个BroadcastReceiver中的代码执行结果。

它只说 Context.sendOrderedBroadcast()因为对 sendBroadcast(...) 方法的常规调用可能不会等待 1 个接收器完成其执行,然后再启动另一个线程以在其他接收器中执行代码,这些接收器也监听相同的 Intent 。

关于android - 为什么要在 BroadcastReceiver 中调用 setResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8990671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com