FragmentActivity.java revision 0adacc1aa313d757ae1c517152cef838e0f35c13
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.v4.app;
18
19import android.app.Activity;
20import android.content.Context;
21import android.content.Intent;
22import android.content.res.Configuration;
23import android.content.res.Resources;
24import android.content.res.TypedArray;
25import android.os.Bundle;
26import android.os.Handler;
27import android.os.Message;
28import android.os.Parcelable;
29import android.support.v4.util.SparseArrayCompat;
30import android.util.AttributeSet;
31import android.util.Log;
32import android.view.KeyEvent;
33import android.view.Menu;
34import android.view.MenuItem;
35import android.view.View;
36import android.view.ViewGroup;
37import android.view.Window;
38
39import java.io.FileDescriptor;
40import java.io.PrintWriter;
41import java.util.ArrayList;
42import java.util.HashMap;
43
44/**
45 * Base class for activities that want to use the support-based
46 * {@link android.support.v4.app.Fragment} and
47 * {@link android.support.v4.content.Loader} APIs.
48 *
49 * <p>When using this class as opposed to new platform's built-in fragment
50 * and loader support, you must use the {@link #getSupportFragmentManager()}
51 * and {@link #getSupportLoaderManager()} methods respectively to access
52 * those features.
53 *
54 * <p>Known limitations:</p>
55 * <ul>
56 * <li> <p>When using the &lt;fragment> tag, this implementation can not
57 * use the parent view's ID as the new fragment's ID.  You must explicitly
58 * specify an ID (or tag) in the &lt;fragment>.</p>
59 * <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
60 * Fragments are a significant amount of new state, and dynamic enough that one
61 * often wants them to change between pausing and stopping.  These classes
62 * throw an exception if you try to change the fragment state after it has been
63 * saved, to avoid accidental loss of UI state.  However this is too restrictive
64 * prior to Honeycomb, where the state is saved before pausing.  To address this,
65 * when running on platforms prior to Honeycomb an exception will not be thrown
66 * if you change fragments between the state save and the activity being stopped.
67 * This means that in some cases if the activity is restored from its last saved
68 * state, this may be a snapshot slightly before what the user last saw.</p>
69 * </ul>
70 */
71public class FragmentActivity extends Activity {
72    private static final String TAG = "FragmentActivity";
73
74    static final String FRAGMENTS_TAG = "android:support:fragments";
75
76    // This is the SDK API version of Honeycomb (3.0).
77    private static final int HONEYCOMB = 11;
78
79    static final int MSG_REALLY_STOPPED = 1;
80    static final int MSG_RESUME_PENDING = 2;
81
82    final Handler mHandler = new Handler() {
83        @Override
84        public void handleMessage(Message msg) {
85            switch (msg.what) {
86                case MSG_REALLY_STOPPED:
87                    if (mStopped) {
88                        doReallyStop(false);
89                    }
90                    break;
91                case MSG_RESUME_PENDING:
92                    onResumeFragments();
93                    mFragments.execPendingActions();
94                    break;
95                default:
96                    super.handleMessage(msg);
97            }
98        }
99
100    };
101    final FragmentManagerImpl mFragments = new FragmentManagerImpl();
102    final FragmentContainer mContainer = new FragmentContainer() {
103        @Override
104        public View findViewById(int id) {
105            return FragmentActivity.this.findViewById(id);
106        }
107    };
108
109    boolean mCreated;
110    boolean mResumed;
111    boolean mStopped;
112    boolean mReallyStopped;
113    boolean mRetaining;
114
115    boolean mOptionsMenuInvalidated;
116
117    boolean mCheckedForLoaderManager;
118    boolean mLoadersStarted;
119    HashMap<String, LoaderManagerImpl> mAllLoaderManagers;
120    LoaderManagerImpl mLoaderManager;
121
122    static final class NonConfigurationInstances {
123        Object activity;
124        Object custom;
125        HashMap<String, Object> children;
126        ArrayList<Fragment> fragments;
127        HashMap<String, LoaderManagerImpl> loaders;
128    }
129
130    static class FragmentTag {
131        public static final int[] Fragment = {
132            0x01010003, 0x010100d0, 0x010100d1
133        };
134        public static final int Fragment_id = 1;
135        public static final int Fragment_name = 0;
136        public static final int Fragment_tag = 2;
137    }
138
139    // ------------------------------------------------------------------------
140    // HOOKS INTO ACTIVITY
141    // ------------------------------------------------------------------------
142
143    /**
144     * Dispatch incoming result to the correct fragment.
145     */
146    @Override
147    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
148        int index = requestCode>>16;
149        if (index != 0) {
150            index--;
151            if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
152                Log.w(TAG, "Activity result fragment index out of range: 0x"
153                        + Integer.toHexString(requestCode));
154                return;
155            }
156            Fragment frag = mFragments.mActive.get(index);
157            if (frag == null) {
158                Log.w(TAG, "Activity result no fragment exists for index: 0x"
159                        + Integer.toHexString(requestCode));
160            } else {
161                frag.onActivityResult(requestCode&0xffff, resultCode, data);
162            }
163            return;
164        }
165
166        super.onActivityResult(requestCode, resultCode, data);
167    }
168
169    /**
170     * Take care of popping the fragment back stack or finishing the activity
171     * as appropriate.
172     */
173    public void onBackPressed() {
174        if (!mFragments.popBackStackImmediate()) {
175            finish();
176        }
177    }
178
179    /**
180     * Dispatch configuration change to all fragments.
181     */
182    @Override
183    public void onConfigurationChanged(Configuration newConfig) {
184        super.onConfigurationChanged(newConfig);
185        mFragments.dispatchConfigurationChanged(newConfig);
186    }
187
188    /**
189     * Perform initialization of all fragments and loaders.
190     */
191    @Override
192    protected void onCreate(Bundle savedInstanceState) {
193        mFragments.attachActivity(this, mContainer, null);
194        // Old versions of the platform didn't do this!
195        if (getLayoutInflater().getFactory() == null) {
196            getLayoutInflater().setFactory(this);
197        }
198
199        super.onCreate(savedInstanceState);
200
201        NonConfigurationInstances nc = (NonConfigurationInstances)
202                getLastNonConfigurationInstance();
203        if (nc != null) {
204            mAllLoaderManagers = nc.loaders;
205        }
206        if (savedInstanceState != null) {
207            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
208            mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
209        }
210        mFragments.dispatchCreate();
211    }
212
213    /**
214     * Dispatch to Fragment.onCreateOptionsMenu().
215     */
216    @Override
217    public boolean onCreatePanelMenu(int featureId, Menu menu) {
218        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
219            boolean show = super.onCreatePanelMenu(featureId, menu);
220            show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
221            if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
222                return show;
223            }
224            // Prior to Honeycomb, the framework can't invalidate the options
225            // menu, so we must always say we have one in case the app later
226            // invalidates it and needs to have it shown.
227            return true;
228        }
229        return super.onCreatePanelMenu(featureId, menu);
230    }
231
232    /**
233     * Add support for inflating the &lt;fragment> tag.
234     */
235    @Override
236    public View onCreateView(String name, Context context, AttributeSet attrs) {
237        if (!"fragment".equals(name)) {
238            return super.onCreateView(name, context, attrs);
239        }
240
241        String fname = attrs.getAttributeValue(null, "class");
242        TypedArray a =  context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
243        if (fname == null) {
244            fname = a.getString(FragmentTag.Fragment_name);
245        }
246        int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
247        String tag = a.getString(FragmentTag.Fragment_tag);
248        a.recycle();
249
250        View parent = null; // NOTE: no way to get parent pre-Honeycomb.
251        int containerId = parent != null ? parent.getId() : 0;
252        if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
253            throw new IllegalArgumentException(attrs.getPositionDescription()
254                    + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
255        }
256
257        // If we restored from a previous state, we may already have
258        // instantiated this fragment from the state and should use
259        // that instance instead of making a new one.
260        Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
261        if (fragment == null && tag != null) {
262            fragment = mFragments.findFragmentByTag(tag);
263        }
264        if (fragment == null && containerId != View.NO_ID) {
265            fragment = mFragments.findFragmentById(containerId);
266        }
267
268        if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
269                + Integer.toHexString(id) + " fname=" + fname
270                + " existing=" + fragment);
271        if (fragment == null) {
272            fragment = Fragment.instantiate(this, fname);
273            fragment.mFromLayout = true;
274            fragment.mFragmentId = id != 0 ? id : containerId;
275            fragment.mContainerId = containerId;
276            fragment.mTag = tag;
277            fragment.mInLayout = true;
278            fragment.mFragmentManager = mFragments;
279            fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
280            mFragments.addFragment(fragment, true);
281
282        } else if (fragment.mInLayout) {
283            // A fragment already exists and it is not one we restored from
284            // previous state.
285            throw new IllegalArgumentException(attrs.getPositionDescription()
286                    + ": Duplicate id 0x" + Integer.toHexString(id)
287                    + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
288                    + " with another fragment for " + fname);
289        } else {
290            // This fragment was retained from a previous instance; get it
291            // going now.
292            fragment.mInLayout = true;
293            // If this fragment is newly instantiated (either right now, or
294            // from last saved state), then give it the attributes to
295            // initialize itself.
296            if (!fragment.mRetaining) {
297                fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
298            }
299            mFragments.moveToState(fragment);
300        }
301
302        if (fragment.mView == null) {
303            throw new IllegalStateException("Fragment " + fname
304                    + " did not create a view.");
305        }
306        if (id != 0) {
307            fragment.mView.setId(id);
308        }
309        if (fragment.mView.getTag() == null) {
310            fragment.mView.setTag(tag);
311        }
312        return fragment.mView;
313    }
314
315    /**
316     * Destroy all fragments and loaders.
317     */
318    @Override
319    protected void onDestroy() {
320        super.onDestroy();
321
322        doReallyStop(false);
323
324        mFragments.dispatchDestroy();
325        if (mLoaderManager != null) {
326            mLoaderManager.doDestroy();
327        }
328    }
329
330    /**
331     * Take care of calling onBackPressed() for pre-Eclair platforms.
332     */
333    @Override
334    public boolean onKeyDown(int keyCode, KeyEvent event) {
335        if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
336                && keyCode == KeyEvent.KEYCODE_BACK
337                && event.getRepeatCount() == 0) {
338            // Take care of calling this method on earlier versions of
339            // the platform where it doesn't exist.
340            onBackPressed();
341            return true;
342        }
343
344        return super.onKeyDown(keyCode, event);
345    }
346
347    /**
348     * Dispatch onLowMemory() to all fragments.
349     */
350    @Override
351    public void onLowMemory() {
352        super.onLowMemory();
353        mFragments.dispatchLowMemory();
354    }
355
356    /**
357     * Dispatch context and options menu to fragments.
358     */
359    @Override
360    public boolean onMenuItemSelected(int featureId, MenuItem item) {
361        if (super.onMenuItemSelected(featureId, item)) {
362            return true;
363        }
364
365        switch (featureId) {
366            case Window.FEATURE_OPTIONS_PANEL:
367                return mFragments.dispatchOptionsItemSelected(item);
368
369            case Window.FEATURE_CONTEXT_MENU:
370                return mFragments.dispatchContextItemSelected(item);
371
372            default:
373                return false;
374        }
375    }
376
377    /**
378     * Call onOptionsMenuClosed() on fragments.
379     */
380    @Override
381    public void onPanelClosed(int featureId, Menu menu) {
382        switch (featureId) {
383            case Window.FEATURE_OPTIONS_PANEL:
384                mFragments.dispatchOptionsMenuClosed(menu);
385                break;
386        }
387        super.onPanelClosed(featureId, menu);
388    }
389
390    /**
391     * Dispatch onPause() to fragments.
392     */
393    @Override
394    protected void onPause() {
395        super.onPause();
396        mResumed = false;
397        if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
398            mHandler.removeMessages(MSG_RESUME_PENDING);
399            onResumeFragments();
400        }
401        mFragments.dispatchPause();
402    }
403
404    /**
405     * Dispatch onResume() to fragments.  Note that for better inter-operation
406     * with older versions of the platform, at the point of this call the
407     * fragments attached to the activity are <em>not</em> resumed.  This means
408     * that in some cases the previous state may still be saved, not allowing
409     * fragment transactions that modify the state.  To correctly interact
410     * with fragments in their proper state, you should instead override
411     * {@link #onResumeFragments()}.
412     */
413    @Override
414    protected void onResume() {
415        super.onResume();
416        mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
417        mResumed = true;
418        mFragments.execPendingActions();
419    }
420
421    /**
422     * Dispatch onResume() to fragments.
423     */
424    @Override
425    protected void onPostResume() {
426        super.onPostResume();
427        mHandler.removeMessages(MSG_RESUME_PENDING);
428        onResumeFragments();
429        mFragments.execPendingActions();
430    }
431
432    /**
433     * This is the fragment-orientated version of {@link #onResume()} that you
434     * can override to perform operations in the Activity at the same point
435     * where its fragments are resumed.  Be sure to always call through to
436     * the super-class.
437     */
438    protected void onResumeFragments() {
439        mFragments.dispatchResume();
440    }
441
442    /**
443     * Dispatch onPrepareOptionsMenu() to fragments.
444     */
445    @Override
446    public boolean onPreparePanel(int featureId, View view, Menu menu) {
447        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
448            if (mOptionsMenuInvalidated) {
449                mOptionsMenuInvalidated = false;
450                menu.clear();
451                onCreatePanelMenu(featureId, menu);
452            }
453            boolean goforit = super.onPreparePanel(featureId, view, menu);
454            goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
455            return goforit && menu.hasVisibleItems();
456        }
457        return super.onPreparePanel(featureId, view, menu);
458    }
459
460    /**
461     * Retain all appropriate fragment and loader state.  You can NOT
462     * override this yourself!  Use {@link #onRetainCustomNonConfigurationInstance()}
463     * if you want to retain your own state.
464     */
465    @Override
466    public final Object onRetainNonConfigurationInstance() {
467        if (mStopped) {
468            doReallyStop(true);
469        }
470
471        Object custom = onRetainCustomNonConfigurationInstance();
472
473        ArrayList<Fragment> fragments = mFragments.retainNonConfig();
474        boolean retainLoaders = false;
475        if (mAllLoaderManagers != null) {
476            // prune out any loader managers that were already stopped and so
477            // have nothing useful to retain.
478            LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
479            mAllLoaderManagers.values().toArray(loaders);
480            if (loaders != null) {
481                for (int i=0; i<loaders.length; i++) {
482                    LoaderManagerImpl lm = loaders[i];
483                    if (lm.mRetaining) {
484                        retainLoaders = true;
485                    } else {
486                        lm.doDestroy();
487                        mAllLoaderManagers.remove(lm.mWho);
488                    }
489                }
490            }
491        }
492        if (fragments == null && !retainLoaders && custom == null) {
493            return null;
494        }
495
496        NonConfigurationInstances nci = new NonConfigurationInstances();
497        nci.activity = null;
498        nci.custom = custom;
499        nci.children = null;
500        nci.fragments = fragments;
501        nci.loaders = mAllLoaderManagers;
502        return nci;
503    }
504
505    /**
506     * Save all appropriate fragment state.
507     */
508    @Override
509    protected void onSaveInstanceState(Bundle outState) {
510        super.onSaveInstanceState(outState);
511        Parcelable p = mFragments.saveAllState();
512        if (p != null) {
513            outState.putParcelable(FRAGMENTS_TAG, p);
514        }
515    }
516
517    /**
518     * Dispatch onStart() to all fragments.  Ensure any created loaders are
519     * now started.
520     */
521    @Override
522    protected void onStart() {
523        super.onStart();
524
525        mStopped = false;
526        mReallyStopped = false;
527        mHandler.removeMessages(MSG_REALLY_STOPPED);
528
529        if (!mCreated) {
530            mCreated = true;
531            mFragments.dispatchActivityCreated();
532        }
533
534        mFragments.noteStateNotSaved();
535        mFragments.execPendingActions();
536
537        if (!mLoadersStarted) {
538            mLoadersStarted = true;
539            if (mLoaderManager != null) {
540                mLoaderManager.doStart();
541            } else if (!mCheckedForLoaderManager) {
542                mLoaderManager = getLoaderManager(null, mLoadersStarted, false);
543                // the returned loader manager may be a new one, so we have to start it
544                if ((mLoaderManager != null) && (!mLoaderManager.mStarted)) {
545                    mLoaderManager.doStart();
546                }
547            }
548            mCheckedForLoaderManager = true;
549        }
550        // NOTE: HC onStart goes here.
551
552        mFragments.dispatchStart();
553        if (mAllLoaderManagers != null) {
554            LoaderManagerImpl loaders[] = new LoaderManagerImpl[mAllLoaderManagers.size()];
555            mAllLoaderManagers.values().toArray(loaders);
556            if (loaders != null) {
557                for (int i=0; i<loaders.length; i++) {
558                    LoaderManagerImpl lm = loaders[i];
559                    lm.finishRetain();
560                    lm.doReportStart();
561                }
562            }
563        }
564    }
565
566    /**
567     * Dispatch onStop() to all fragments.  Ensure all loaders are stopped.
568     */
569    @Override
570    protected void onStop() {
571        super.onStop();
572
573        mStopped = true;
574        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
575
576        mFragments.dispatchStop();
577    }
578
579    // ------------------------------------------------------------------------
580    // NEW METHODS
581    // ------------------------------------------------------------------------
582
583    /**
584     * Use this instead of {@link #onRetainNonConfigurationInstance()}.
585     * Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
586     */
587    public Object onRetainCustomNonConfigurationInstance() {
588        return null;
589    }
590
591    /**
592     * Return the value previously returned from
593     * {@link #onRetainCustomNonConfigurationInstance()}.
594     */
595    public Object getLastCustomNonConfigurationInstance() {
596        NonConfigurationInstances nc = (NonConfigurationInstances)
597                getLastNonConfigurationInstance();
598        return nc != null ? nc.custom : null;
599    }
600
601    /**
602     * Invalidate the activity's options menu. This will cause relevant presentations
603     * of the menu to fully update via calls to onCreateOptionsMenu and
604     * onPrepareOptionsMenu the next time the menu is requested.
605     */
606    public void supportInvalidateOptionsMenu() {
607        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
608            // If we are running on HC or greater, we can use the framework
609            // API to invalidate the options menu.
610            ActivityCompatHoneycomb.invalidateOptionsMenu(this);
611            return;
612        }
613
614        // Whoops, older platform...  we'll use a hack, to manually rebuild
615        // the options menu the next time it is prepared.
616        mOptionsMenuInvalidated = true;
617    }
618
619    /**
620     * Print the Activity's state into the given stream.  This gets invoked if
621     * you run "adb shell dumpsys activity <activity_component_name>".
622     *
623     * @param prefix Desired prefix to prepend at each line of output.
624     * @param fd The raw file descriptor that the dump is being sent to.
625     * @param writer The PrintWriter to which you should dump your state.  This will be
626     * closed for you after you return.
627     * @param args additional arguments to the dump request.
628     */
629    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
630        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
631            // XXX This can only work if we can call the super-class impl. :/
632            //ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
633        }
634        writer.print(prefix); writer.print("Local FragmentActivity ");
635                writer.print(Integer.toHexString(System.identityHashCode(this)));
636                writer.println(" State:");
637        String innerPrefix = prefix + "  ";
638        writer.print(innerPrefix); writer.print("mCreated=");
639                writer.print(mCreated); writer.print("mResumed=");
640                writer.print(mResumed); writer.print(" mStopped=");
641                writer.print(mStopped); writer.print(" mReallyStopped=");
642                writer.println(mReallyStopped);
643        writer.print(innerPrefix); writer.print("mLoadersStarted=");
644                writer.println(mLoadersStarted);
645        if (mLoaderManager != null) {
646            writer.print(prefix); writer.print("Loader Manager ");
647                    writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
648                    writer.println(":");
649            mLoaderManager.dump(prefix + "  ", fd, writer, args);
650        }
651        mFragments.dump(prefix, fd, writer, args);
652        writer.print(prefix); writer.println("View Hierarchy:");
653        dumpViewHierarchy(prefix + "  ", writer, getWindow().getDecorView());
654    }
655
656    private static String viewToString(View view) {
657        StringBuilder out = new StringBuilder(128);
658        out.append(view.getClass().getName());
659        out.append('{');
660        out.append(Integer.toHexString(System.identityHashCode(view)));
661        out.append(' ');
662        switch (view.getVisibility()) {
663            case View.VISIBLE: out.append('V'); break;
664            case View.INVISIBLE: out.append('I'); break;
665            case View.GONE: out.append('G'); break;
666            default: out.append('.'); break;
667        }
668        out.append(view.isFocusable() ? 'F' : '.');
669        out.append(view.isEnabled() ? 'E' : '.');
670        out.append(view.willNotDraw() ? '.' : 'D');
671        out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
672        out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
673        out.append(view.isClickable() ? 'C' : '.');
674        out.append(view.isLongClickable() ? 'L' : '.');
675        out.append(' ');
676        out.append(view.isFocused() ? 'F' : '.');
677        out.append(view.isSelected() ? 'S' : '.');
678        out.append(view.isPressed() ? 'P' : '.');
679        out.append(' ');
680        out.append(view.getLeft());
681        out.append(',');
682        out.append(view.getTop());
683        out.append('-');
684        out.append(view.getRight());
685        out.append(',');
686        out.append(view.getBottom());
687        final int id = view.getId();
688        if (id != View.NO_ID) {
689            out.append(" #");
690            out.append(Integer.toHexString(id));
691            final Resources r = view.getResources();
692            if (id != 0 && r != null) {
693                try {
694                    String pkgname;
695                    switch (id&0xff000000) {
696                        case 0x7f000000:
697                            pkgname="app";
698                            break;
699                        case 0x01000000:
700                            pkgname="android";
701                            break;
702                        default:
703                            pkgname = r.getResourcePackageName(id);
704                            break;
705                    }
706                    String typename = r.getResourceTypeName(id);
707                    String entryname = r.getResourceEntryName(id);
708                    out.append(" ");
709                    out.append(pkgname);
710                    out.append(":");
711                    out.append(typename);
712                    out.append("/");
713                    out.append(entryname);
714                } catch (Resources.NotFoundException e) {
715                }
716            }
717        }
718        out.append("}");
719        return out.toString();
720    }
721
722    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
723        writer.print(prefix);
724        if (view == null) {
725            writer.println("null");
726            return;
727        }
728        writer.println(viewToString(view));
729        if (!(view instanceof ViewGroup)) {
730            return;
731        }
732        ViewGroup grp = (ViewGroup)view;
733        final int N = grp.getChildCount();
734        if (N <= 0) {
735            return;
736        }
737        prefix = prefix + "  ";
738        for (int i=0; i<N; i++) {
739            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
740        }
741    }
742
743    void doReallyStop(boolean retaining) {
744        if (!mReallyStopped) {
745            mReallyStopped = true;
746            mRetaining = retaining;
747            mHandler.removeMessages(MSG_REALLY_STOPPED);
748            onReallyStop();
749        }
750    }
751
752    /**
753     * Pre-HC, we didn't have a way to determine whether an activity was
754     * being stopped for a config change or not until we saw
755     * onRetainNonConfigurationInstance() called after onStop().  However
756     * we need to know this, to know whether to retain fragments.  This will
757     * tell us what we need to know.
758     */
759    void onReallyStop() {
760        if (mLoadersStarted) {
761            mLoadersStarted = false;
762            if (mLoaderManager != null) {
763                if (!mRetaining) {
764                    mLoaderManager.doStop();
765                } else {
766                    mLoaderManager.doRetain();
767                }
768            }
769        }
770
771        mFragments.dispatchReallyStop();
772    }
773
774    // ------------------------------------------------------------------------
775    // FRAGMENT SUPPORT
776    // ------------------------------------------------------------------------
777
778    /**
779     * Called when a fragment is attached to the activity.
780     */
781    public void onAttachFragment(Fragment fragment) {
782    }
783
784    /**
785     * Return the FragmentManager for interacting with fragments associated
786     * with this activity.
787     */
788    public FragmentManager getSupportFragmentManager() {
789        return mFragments;
790    }
791
792    /**
793     * Modifies the standard behavior to allow results to be delivered to fragments.
794     * This imposes a restriction that requestCode be <= 0xffff.
795     */
796    @Override
797    public void startActivityForResult(Intent intent, int requestCode) {
798        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
799            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
800        }
801        super.startActivityForResult(intent, requestCode);
802    }
803
804    /**
805     * Called by Fragment.startActivityForResult() to implement its behavior.
806     */
807    public void startActivityFromFragment(Fragment fragment, Intent intent,
808            int requestCode) {
809        if (requestCode == -1) {
810            super.startActivityForResult(intent, -1);
811            return;
812        }
813        if ((requestCode&0xffff0000) != 0) {
814            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
815        }
816        super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
817    }
818
819    void invalidateSupportFragment(String who) {
820        //Log.v(TAG, "invalidateSupportFragment: who=" + who);
821        if (mAllLoaderManagers != null) {
822            LoaderManagerImpl lm = mAllLoaderManagers.get(who);
823            if (lm != null && !lm.mRetaining) {
824                lm.doDestroy();
825                mAllLoaderManagers.remove(who);
826            }
827        }
828    }
829
830    // ------------------------------------------------------------------------
831    // LOADER SUPPORT
832    // ------------------------------------------------------------------------
833
834    /**
835     * Return the LoaderManager for this fragment, creating it if needed.
836     */
837    public LoaderManager getSupportLoaderManager() {
838        if (mLoaderManager != null) {
839            return mLoaderManager;
840        }
841        mCheckedForLoaderManager = true;
842        mLoaderManager = getLoaderManager(null, mLoadersStarted, true);
843        return mLoaderManager;
844    }
845
846    LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
847        if (mAllLoaderManagers == null) {
848            mAllLoaderManagers = new HashMap<String, LoaderManagerImpl>();
849        }
850        LoaderManagerImpl lm = mAllLoaderManagers.get(who);
851        if (lm == null) {
852            if (create) {
853                lm = new LoaderManagerImpl(who, this, started);
854                mAllLoaderManagers.put(who, lm);
855            }
856        } else {
857            lm.updateActivity(this);
858        }
859        return lm;
860    }
861}
862