gpt4 book ai didi

java - android LocalBroadcast的两个接收者,一个在MainActivity中,另一个在fragment中

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:07 25 4
gpt4 key购买 nike

在Android应用程序中,我在MainActivity的onCreate中注册了一个接收器

IntentFilter mFilter = new IntentFilter("Action");
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, mFilter);

在其 onResume 中

new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent i = new Intent("Action");
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(i);
}
});
}
}).start();

坦白说,我不确定为什么我们要使用这样的线程(我从某个地方复制了代码,但没有完全消化它)。

此应用程序支持 ViewPager,因此在其关联的 Fragment 的 onCreate 中

    IntentFilter mFilter = new IntentFilter("Action");
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, mFilter);

在 MainActivity 和 Fragment 类中,接收器如下所示:

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
...
}

两个类中只有 onReceive 内部的内容不同。

我不太了解 LocalBroadcast 是如何工作的,我期望一旦发出广播,两个接收器处理程序都会运行。相反,我注意到大多数时候只有 MainActivity 中的接收器运行,偶尔 fragment 类中的接收器运行。

我的预感是与线程部分有关。

最佳答案

这种行为背后的原因可能是Activity 和 Fragment 的生命周期:

根据我的经验,当您有 Activity+Fragment 时,如何调用方法是:

  1. Activity 的onCreate()
  2. Activity 的onStart()
  3. Activity 的onResume()
  4. Fragment 的 onCreateView()
  5. Fragment 的 onStart()
  6. fragment 的onResume()

Explanation :

As your Fragment is not initialized yet when you are broadcasting from onResume() in Activity it could not be received at first by The Fragment but only receive by Activity. After that once the fragment is initialized the Broadcast will be received by the Fragment also.

关于java - android LocalBroadcast的两个接收者,一个在MainActivity中,另一个在fragment中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759824/

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