1

在一个 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 中的接收器运行,偶尔在片段类中运行。

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

4

1 回答 1

0

The reason behind Such behavior can be the Lifecycle of Both Activity as well as Fragment:

As per my experience how the methods get called when you have Activity+Fragment is:

  1. Activity's onCreate()
  2. Activity's onStart()
  3. Activity's onResume()
  4. Fragment's onCreateView()
  5. Fragment's onStart()
  6. Fragment's 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.

于 2016-06-11T05:31:04.977 回答