Android8.0 Fragment变化之setTargetFragment

此问题源于一个FATAL异常:

AndroidRuntime: FATAL EXCEPTION: main
AndroidRuntime: Process: com.android.settings, PID: 3449
AndroidRuntime: java.lang.IllegalStateException: Fragment RunningServiceDetails{3b9137f #4 id=0x100b0002 com.android.settings.applications.RunningServiceDetails} declared target fragment RunningApplicationsFragment{2d46d8c #2 id=0x100b0000 2131887823} that does not belong to this FragmentManager!
AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1212)
AndroidRuntime:     at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
AndroidRuntime:     at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
AndroidRuntime:     at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
AndroidRuntime:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
AndroidRuntime:     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:790)
AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
AndroidRuntime:     at android.os.Looper.loop(Looper.java:164)
AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6601)
AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
AndroidRuntime:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:518)
AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:822)
ActivityManager:   Force finishing activity com.android.settings/.MainSettings

看异常信息为:申明的target Fragment 不属于当前的FragmentManager,然而在N上以及N以下都没有这个问题,我们看一下该异常是由哪边报的:

FragmentManager中:

f.mHost = mHost;
f.mParentFragment = mParent;
f.mFragmentManager = mParent != null
        ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl();

// If we have a target fragment, push it along to at least CREATED
// so that this one can rely on it as an initialized dependency.
if (f.mTarget != null) {
    if (mActive.get(f.mTarget.mIndex) != f.mTarget) {
        throw new IllegalStateException("Fragment " + f
                + " declared target fragment " + f.mTarget
                + " that does not belong to this FragmentManager!");
    }
    if (f.mTarget.mState < Fragment.CREATED) {
        moveToState(f.mTarget, Fragment.CREATED, 0, 0, true);
    }
}

通过git blame 看一下这块代码的提交:

git blame core/java/android/app/FragmentManager.java

ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1204)
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1205)  // If we have a target fragment, push it along to at least CREATED
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1206)  // so that this one can rely on it as an initialized dependency.
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1207)  if (f.mTarget != null) {
838166d3e6f8 (George Mount     2017-03-23 14:23:29 -0700 1208)      if (mActive.get(f.mTarget.mIndex) != f.mTarget) {
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1209)          throw new IllegalStateException("Fragment " + f
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1210)                  + " declared target fragment " + f.mTarget
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1211)                  + " that does not belong to this FragmentManager!");
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1212)      }
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1213)      if (f.mTarget.mState < Fragment.CREATED) {
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1214)          moveToState(f.mTarget, Fragment.CREATED, 0, 0, true);
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1215)      }
ab209a63a286 (Adam Powell      2017-01-26 14:14:34 -0800 1216)  }

git log ab209a63a286

可以看到:

commit ab209a63a286ffb0ee57e884986839fa25d583ca
Author: Adam Powell <adamp@google.com>
Date:   Thu Jan 26 14:14:34 2017 -0800

    Lifecycle guarantees for target fragments

    Ported from frameworks/support change id
    I824eb312fbdfd6b548fe94aa2cd5b03afbaa97c7

    When a target fragment was set using Fragment#setTargetFragment, all
    bets were off, especially when restoring from instance state. Order of
    lifecyle initialization was undefined meaning that two bugs could
    occur, both of which manifested as the target fragment was not
    initialized by the time the referring fragment's onCreate ran. One
    could happen if the target fragment is on the back stack, the other
    could happen if the target fragment was ordered unfortunately in
    FragmentManager implementation details. (!)

    Fix both by guaranteeing that any target fragment gets pushed forward
    to at least the CREATED state before we dispatch any lifecycle events
    for the referring fragment.

    Add some sanity checks that try to keep developers from setting target
    fragments across different FragmentManagers or from creating target
    cycles, both of which are bad ideas.

    Bug: 33653458
    Test: CTS FragmentLifecycleTest
    Change-Id: If624d4665d29e205d37b9b384322e64d6d6d3615

再看一下该change到底修改了什么

git show ab209a63a286ffb0ee57e884986839fa25d583ca

diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 73b96f1ba16..612998dd515 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -762,6 +762,24 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
      * are going to call back with {@link #onActivityResult(int, int, Intent)}.
      */
     public void setTargetFragment(Fragment fragment, int requestCode) {
+        // Don't allow a caller to set a target fragment in another FragmentManager,
+        // but there's a snag: people do set target fragments before fragments get added.
+        // We'll have the FragmentManager check that for validity when we move
+        // the fragments to a valid state.
+        final FragmentManager mine = getFragmentManager();
+        final FragmentManager theirs = fragment.getFragmentManager();
+        if (mine != null && theirs != null && mine != theirs) {
+            throw new IllegalArgumentException("Fragment " + fragment
+                    + " must share the same FragmentManager to be set as a target fragment");
+        }
+
+        // Don't let someone create a cycle.
+        for (Fragment check = fragment; check != null; check = check.getTargetFragment()) {
+            if (check == this) {
+                throw new IllegalArgumentException("Setting " + fragment + " as the target of "
+                        + this + " would create a target cycle");
+            }
+        }
         mTarget = fragment;
         mTargetRequestCode = requestCode;
     }
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 44f1322f4b4..32cf1c341b4 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -1110,10 +1110,25 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
                                 }
                             }
                         }
+
                         f.mHost = mHost;
                         f.mParentFragment = mParent;
                         f.mFragmentManager = mParent != null
                                 ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl();
+
+                        // If we have a target fragment, push it along to at least CREATED
+                        // so that this one can rely on it as an initialized dependency.
+                        if (f.mTarget != null) {
+                            if (!mActive.contains(f.mTarget)) {
+                                throw new IllegalStateException("Fragment " + f
+                                        + " declared target fragment " + f.mTarget
+                                        + " that does not belong to this FragmentManager!");
+                            }
+                            if (f.mTarget.mState < Fragment.CREATED) {
+                                moveToState(f.mTarget, Fragment.CREATED, 0, 0, true);
+                            }
+                        }
+
                         dispatchOnFragmentPreAttached(f, mHost.getContext(), false);
                         f.mCalled = false;
                         f.onAttach(mHost.getContext());
(END)

我们看到只修改了setTargetFragment,并增加了一个检查,看样子Google在对Fragment的setTargetFragment使用增加限制

我们先看上述问题的原因:

我们在启动Fragment之前给其设置了TargetFragment,这个参数是用来向上一个Fragment传回数据的。

fragment1.setTargetFragment(resultTo, resultRequestCode);

而当前的页面组成其实是:
有两个FragmentManager。一个里面是SettingsFragment与ApplicationContainer
另一个是ManageApplicationFragment1,另一个是ManageApplicationFragment2,RunningApplicationsFragment1, RunningApplicationsFragment2。

事实上,在我们的UI中,是ApplicationContainer包裹着那四个Fragment的

dump当前页面信息

此时我们在被包裹着的 RunningApplicationsFragment 中去启动一个新的Fragment,而使用的FragmentManager为Activity的FragmentManager, 且设置TargetFragment为 RunningApplicationsFragment这个时候FragmentManager会去检查当前的mActive是否包含了这个Fragment,如果没有,则抛出异常。

那么其实我们通过Debug可以看到,当前的FragmentManager其实只有两个子Fragment,而没有 RunningApplicationsFragment, 因此抛出异常。

因此我们在使用Fragment的时候要考虑到现在的O对Fragment增加了使用限制,不再能够随意的嵌套嵌套嵌套,再设置不同的FragmentManager里面的Fragment为targetFragment了


本文作者:Anderson/Jerey_Jobs

博客地址 : http://jerey.cn/
简书地址 : Anderson大码渣
github地址 : https://github.com/Jerey-Jobs

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,214评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,307评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,543评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,221评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,224评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,007评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,313评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,956评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,441评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,925评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,018评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,685评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,234评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,240评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,464评论 1 261
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,467评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,762评论 2 345

推荐阅读更多精彩内容