FragmentActivity.java revision b07179708a404260c65814b0ff14702eef189c01
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.TypedArray;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.Message;
27import android.os.Parcelable;
28import android.util.AttributeSet;
29import android.util.Log;
30import android.view.KeyEvent;
31import android.view.Menu;
32import android.view.MenuItem;
33import android.view.View;
34import android.view.Window;
35
36import java.io.FileDescriptor;
37import java.io.PrintWriter;
38import java.util.ArrayList;
39import java.util.HashMap;
40
41/**
42 * Base class for activities that want to use the support-based Fragment and
43 * Loader APIs.
44 *
45 * <p>Known limitations:</p>
46 * <ul>
47 * <li> <p>When using the &lt;fragment> tag, this implementation can not
48 * use the parent view's ID as the new fragment's ID.  You must explicitly
49 * specify an ID (or tag) in the &lt;fragment>.</p>
50 * <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
51 * Fragments are a significant amount of new state, and dynamic enough that one
52 * often wants them to change between pausing and stopping.  These classes
53 * throw an exception if you try to change the fragment state after it has been
54 * saved, to avoid accidental loss of UI state.  However this is too restrictive
55 * prior to Honeycomb, where the state is saved before pausing.  To address this,
56 * when running on platforms prior to Honeycomb an exception will not be thrown
57 * if you change fragments between the state save and the activity being stopped.
58 * This means that is some cases if the activity is restored from its last saved
59 * state, this may be a snapshot slightly before what the user last saw.</p>
60 * </ul>
61 */
62public class FragmentActivity extends Activity {
63    private static final String TAG = "FragmentActivity";
64
65    private static final String FRAGMENTS_TAG = "android:support:fragments";
66
67    // This is the SDK API version of Honeycomb (3.0).
68    private static final int HONEYCOMB = 11;
69
70    static final int MSG_REALLY_STOPPED = 1;
71    static final int MSG_RESUME_PENDING = 2;
72
73    final Handler mHandler = new Handler() {
74        @Override
75        public void handleMessage(Message msg) {
76            switch (msg.what) {
77                case MSG_REALLY_STOPPED:
78                    if (mStopped) {
79                        doReallyStop(false);
80                    }
81                    break;
82                case MSG_RESUME_PENDING:
83                    mFragments.dispatchResume();
84                    mFragments.execPendingActions();
85                    break;
86                default:
87                    super.handleMessage(msg);
88            }
89        }
90
91    };
92    final FragmentManagerImpl mFragments = new FragmentManagerImpl();
93
94    boolean mCreated;
95    boolean mResumed;
96    boolean mStopped;
97    boolean mReallyStopped;
98    boolean mRetaining;
99
100    boolean mOptionsMenuInvalidated;
101
102    boolean mCheckedForLoaderManager;
103    boolean mLoadersStarted;
104    HCSparseArray<LoaderManagerImpl> mAllLoaderManagers;
105    LoaderManagerImpl mLoaderManager;
106
107    static final class NonConfigurationInstances {
108        Object activity;
109        Object custom;
110        HashMap<String, Object> children;
111        ArrayList<Fragment> fragments;
112        HCSparseArray<LoaderManagerImpl> loaders;
113    }
114
115    static class FragmentTag {
116        public static final int[] Fragment = {
117            0x01010003, 0x010100d0, 0x010100d1
118        };
119        public static final int Fragment_id = 1;
120        public static final int Fragment_name = 0;
121        public static final int Fragment_tag = 2;
122    }
123
124    // ------------------------------------------------------------------------
125    // HOOKS INTO ACTIVITY
126    // ------------------------------------------------------------------------
127
128    /**
129     * Dispatch incoming result to the correct fragment.
130     */
131    @Override
132    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
133        int index = requestCode>>16;
134        if (index != 0) {
135            index--;
136            if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
137                Log.w(TAG, "Activity result fragment index out of range: 0x"
138                        + Integer.toHexString(requestCode));
139                return;
140            }
141            Fragment frag = mFragments.mActive.get(index);
142            if (frag == null) {
143                Log.w(TAG, "Activity result no fragment exists for index: 0x"
144                        + Integer.toHexString(requestCode));
145            }
146            frag.onActivityResult(requestCode&0xffff, resultCode, data);
147            return;
148        }
149
150        super.onActivityResult(requestCode, resultCode, data);
151    }
152
153    /**
154     * Take care of popping the fragment back stack or finishing the activity
155     * as appropriate.
156     */
157    public void onBackPressed() {
158        if (!mFragments.popBackStackImmediate()) {
159            finish();
160        }
161    }
162
163    /**
164     * Dispatch configuration change to all fragments.
165     */
166    @Override
167    public void onConfigurationChanged(Configuration newConfig) {
168        super.onConfigurationChanged(newConfig);
169        mFragments.dispatchConfigurationChanged(newConfig);
170    }
171
172    /**
173     * Perform initialization of all fragments and loaders.
174     */
175    @Override
176    protected void onCreate(Bundle savedInstanceState) {
177        mFragments.attachActivity(this);
178        // Old versions of the platform didn't do this!
179        if (getLayoutInflater().getFactory() == null) {
180            getLayoutInflater().setFactory(this);
181        }
182
183        super.onCreate(savedInstanceState);
184
185        NonConfigurationInstances nc = (NonConfigurationInstances)
186                getLastNonConfigurationInstance();
187        if (nc != null) {
188            mAllLoaderManagers = nc.loaders;
189        }
190        if (savedInstanceState != null) {
191            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
192            mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
193        }
194        mFragments.dispatchCreate();
195    }
196
197    /**
198     * Dispatch to Fragment.onCreateOptionsMenu().
199     */
200    @Override
201    public boolean onCreatePanelMenu(int featureId, Menu menu) {
202        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
203            boolean show = super.onCreatePanelMenu(featureId, menu);
204            show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
205            if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
206                return show;
207            }
208            // Prior to Honeycomb, the framework can't invalidate the options
209            // menu, so we must always say we have one in case the app later
210            // invalidates it and needs to have it shown.
211            return true;
212        }
213        return super.onCreatePanelMenu(featureId, menu);
214    }
215
216    /**
217     * Add support for inflating the &lt;fragment> tag.
218     */
219    @Override
220    public View onCreateView(String name, Context context, AttributeSet attrs) {
221        if (!"fragment".equals(name)) {
222            return super.onCreateView(name, context, attrs);
223        }
224
225        String fname = attrs.getAttributeValue(null, "class");
226        TypedArray a =  context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
227        if (fname == null) {
228            fname = a.getString(FragmentTag.Fragment_name);
229        }
230        int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
231        String tag = a.getString(FragmentTag.Fragment_tag);
232        a.recycle();
233
234        View parent = null; // NOTE: no way to get parent pre-Honeycomb.
235        int containerId = parent != null ? parent.getId() : 0;
236        if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
237            throw new IllegalArgumentException(attrs.getPositionDescription()
238                    + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
239        }
240
241        // If we restored from a previous state, we may already have
242        // instantiated this fragment from the state and should use
243        // that instance instead of making a new one.
244        Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
245        if (fragment == null && tag != null) {
246            fragment = mFragments.findFragmentByTag(tag);
247        }
248        if (fragment == null && containerId != View.NO_ID) {
249            fragment = mFragments.findFragmentById(containerId);
250        }
251
252        if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
253                + Integer.toHexString(id) + " fname=" + fname
254                + " existing=" + fragment);
255        if (fragment == null) {
256            fragment = Fragment.instantiate(this, fname);
257            fragment.mFromLayout = true;
258            fragment.mFragmentId = id != 0 ? id : containerId;
259            fragment.mContainerId = containerId;
260            fragment.mTag = tag;
261            fragment.mInLayout = true;
262            fragment.mFragmentManager = mFragments;
263            fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
264            mFragments.addFragment(fragment, true);
265
266        } else if (fragment.mInLayout) {
267            // A fragment already exists and it is not one we restored from
268            // previous state.
269            throw new IllegalArgumentException(attrs.getPositionDescription()
270                    + ": Duplicate id 0x" + Integer.toHexString(id)
271                    + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
272                    + " with another fragment for " + fname);
273        } else {
274            // This fragment was retained from a previous instance; get it
275            // going now.
276            fragment.mInLayout = true;
277            // If this fragment is newly instantiated (either right now, or
278            // from last saved state), then give it the attributes to
279            // initialize itself.
280            if (!fragment.mRetaining) {
281                fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
282            }
283            mFragments.moveToState(fragment);
284        }
285
286        if (fragment.mView == null) {
287            throw new IllegalStateException("Fragment " + fname
288                    + " did not create a view.");
289        }
290        if (id != 0) {
291            fragment.mView.setId(id);
292        }
293        if (fragment.mView.getTag() == null) {
294            fragment.mView.setTag(tag);
295        }
296        return fragment.mView;
297    }
298
299    /**
300     * Destroy all fragments and loaders.
301     */
302    @Override
303    protected void onDestroy() {
304        super.onDestroy();
305
306        doReallyStop(false);
307
308        mFragments.dispatchDestroy();
309        if (mLoaderManager != null) {
310            mLoaderManager.doDestroy();
311        }
312    }
313
314    /**
315     * Take care of calling onBackPressed() for pre-Eclair platforms.
316     */
317    @Override
318    public boolean onKeyDown(int keyCode, KeyEvent event) {
319        if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
320                && keyCode == KeyEvent.KEYCODE_BACK
321                && event.getRepeatCount() == 0) {
322            // Take care of calling this method on earlier versions of
323            // the platform where it doesn't exist.
324            onBackPressed();
325            return true;
326        }
327
328        return super.onKeyDown(keyCode, event);
329    }
330
331    /**
332     * Dispatch onLowMemory() to all fragments.
333     */
334    @Override
335    public void onLowMemory() {
336        super.onLowMemory();
337        mFragments.dispatchLowMemory();
338    }
339
340    /**
341     * Dispatch context and options menu to fragments.
342     */
343    @Override
344    public boolean onMenuItemSelected(int featureId, MenuItem item) {
345        if (super.onMenuItemSelected(featureId, item)) {
346            return true;
347        }
348
349        switch (featureId) {
350            case Window.FEATURE_OPTIONS_PANEL:
351                return mFragments.dispatchOptionsItemSelected(item);
352
353            case Window.FEATURE_CONTEXT_MENU:
354                return mFragments.dispatchContextItemSelected(item);
355
356            default:
357                return false;
358        }
359    }
360
361    /**
362     * Call onOptionsMenuClosed() on fragments.
363     */
364    @Override
365    public void onPanelClosed(int featureId, Menu menu) {
366        switch (featureId) {
367            case Window.FEATURE_OPTIONS_PANEL:
368                mFragments.dispatchOptionsMenuClosed(menu);
369                break;
370        }
371        super.onPanelClosed(featureId, menu);
372    }
373
374    /**
375     * Dispatch onPause() to fragments.
376     */
377    @Override
378    protected void onPause() {
379        super.onPause();
380        mResumed = false;
381        if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
382            mHandler.removeMessages(MSG_RESUME_PENDING);
383            mFragments.dispatchResume();
384        }
385        mFragments.dispatchPause();
386    }
387
388    /**
389     * Dispatch onResume() to fragments.
390     */
391    @Override
392    protected void onResume() {
393        super.onResume();
394        mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
395        mResumed = true;
396        mFragments.execPendingActions();
397    }
398
399    /**
400     * Dispatch onResume() to fragments.
401     */
402    @Override
403    protected void onPostResume() {
404        super.onPostResume();
405        mHandler.removeMessages(MSG_RESUME_PENDING);
406        mFragments.dispatchResume();
407        mFragments.execPendingActions();
408    }
409
410    /**
411     * Dispatch onPrepareOptionsMenu() to fragments.
412     */
413    @Override
414    public boolean onPreparePanel(int featureId, View view, Menu menu) {
415        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
416            if (mOptionsMenuInvalidated) {
417                mOptionsMenuInvalidated = false;
418                menu.clear();
419                onCreatePanelMenu(featureId, menu);
420            }
421            boolean goforit = super.onPreparePanel(featureId, view, menu);
422            goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
423            return goforit && menu.hasVisibleItems();
424        }
425        return super.onPreparePanel(featureId, view, menu);
426    }
427
428    /**
429     * Retain all appropriate fragment and loader state.  You can NOT
430     * override this yourself!  Use {@link #onRetainCustomNonConfigurationInstance()}
431     * if you want to retain your own state.
432     */
433    @Override
434    public final Object onRetainNonConfigurationInstance() {
435        if (mStopped) {
436            doReallyStop(true);
437        }
438
439        Object custom = onRetainCustomNonConfigurationInstance();
440
441        ArrayList<Fragment> fragments = mFragments.retainNonConfig();
442        boolean retainLoaders = false;
443        if (mAllLoaderManagers != null) {
444            // prune out any loader managers that were already stopped and so
445            // have nothing useful to retain.
446            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
447                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
448                if (lm.mRetaining) {
449                    retainLoaders = true;
450                } else {
451                    lm.doDestroy();
452                    mAllLoaderManagers.removeAt(i);
453                }
454            }
455        }
456        if (fragments == null && !retainLoaders && custom == null) {
457            return null;
458        }
459
460        NonConfigurationInstances nci = new NonConfigurationInstances();
461        nci.activity = null;
462        nci.custom = custom;
463        nci.children = null;
464        nci.fragments = fragments;
465        nci.loaders = mAllLoaderManagers;
466        return nci;
467    }
468
469    /**
470     * Save all appropriate fragment state.
471     */
472    @Override
473    protected void onSaveInstanceState(Bundle outState) {
474        super.onSaveInstanceState(outState);
475        Parcelable p = mFragments.saveAllState();
476        if (p != null) {
477            outState.putParcelable(FRAGMENTS_TAG, p);
478        }
479    }
480
481    /**
482     * Dispatch onStart() to all fragments.  Ensure any created loaders are
483     * now started.
484     */
485    @Override
486    protected void onStart() {
487        super.onStart();
488
489        mStopped = false;
490        mReallyStopped = false;
491        mHandler.removeMessages(MSG_REALLY_STOPPED);
492
493        if (!mCreated) {
494            mCreated = true;
495            mFragments.dispatchActivityCreated();
496        }
497
498        mFragments.noteStateNotSaved();
499        mFragments.execPendingActions();
500
501        if (!mLoadersStarted) {
502            mLoadersStarted = true;
503            if (mLoaderManager != null) {
504                mLoaderManager.doStart();
505            } else if (!mCheckedForLoaderManager) {
506                mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
507            }
508            mCheckedForLoaderManager = true;
509        }
510        // NOTE: HC onStart goes here.
511
512        mFragments.dispatchStart();
513        if (mAllLoaderManagers != null) {
514            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
515                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
516                lm.finishRetain();
517                lm.doReportStart();
518            }
519        }
520    }
521
522    /**
523     * Dispatch onStop() to all fragments.  Ensure all loaders are stopped.
524     */
525    @Override
526    protected void onStop() {
527        super.onStop();
528
529        mStopped = true;
530        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
531
532        mFragments.dispatchStop();
533    }
534
535    // ------------------------------------------------------------------------
536    // NEW METHODS
537    // ------------------------------------------------------------------------
538
539    /**
540     * Use this instead of {@link #onRetainNonConfigurationInstance()}.
541     * Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
542     */
543    public Object onRetainCustomNonConfigurationInstance() {
544        return null;
545    }
546
547    /**
548     * Return the value previously returned from
549     * {@link #onRetainCustomNonConfigurationInstance()}.
550     */
551    public Object getLastCustomNonConfigurationInstance() {
552        NonConfigurationInstances nc = (NonConfigurationInstances)
553                getLastNonConfigurationInstance();
554        return nc != null ? nc.custom : null;
555    }
556
557    void supportInvalidateOptionsMenu() {
558        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
559            // If we are running on HC or greater, we can use the framework
560            // API to invalidate the options menu.
561            ActivityCompatHoneycomb.invalidateOptionsMenu(this);
562            return;
563        }
564
565        // Whoops, older platform...  we'll use a hack, to manually rebuild
566        // the options menu the next time it is prepared.
567        mOptionsMenuInvalidated = true;
568    }
569
570    /**
571     * Print the Activity's state into the given stream.  This gets invoked if
572     * you run "adb shell dumpsys activity <activity_component_name>".
573     *
574     * @param prefix Desired prefix to prepend at each line of output.
575     * @param fd The raw file descriptor that the dump is being sent to.
576     * @param writer The PrintWriter to which you should dump your state.  This will be
577     * closed for you after you return.
578     * @param args additional arguments to the dump request.
579     */
580    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
581        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
582            // XXX This can only work if we can call the super-class impl. :/
583            //ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
584        }
585        writer.print(prefix); writer.print("Local FragmentActivity ");
586                writer.print(Integer.toHexString(System.identityHashCode(this)));
587                writer.println(" State:");
588        String innerPrefix = prefix + "  ";
589        writer.print(innerPrefix); writer.print("mCreated=");
590                writer.print(mCreated); writer.print("mResumed=");
591                writer.print(mResumed); writer.print(" mStopped=");
592                writer.print(mStopped); writer.print(" mReallyStopped=");
593                writer.println(mReallyStopped);
594        writer.print(innerPrefix); writer.print("mLoadersStarted=");
595                writer.println(mLoadersStarted);
596        if (mLoaderManager != null) {
597            writer.print(prefix); writer.print("Loader Manager ");
598                    writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
599                    writer.println(":");
600            mLoaderManager.dump(prefix + "  ", fd, writer, args);
601        }
602        mFragments.dump(prefix, fd, writer, args);
603    }
604
605    void doReallyStop(boolean retaining) {
606        if (!mReallyStopped) {
607            mReallyStopped = true;
608            mRetaining = retaining;
609            mHandler.removeMessages(MSG_REALLY_STOPPED);
610            onReallyStop();
611        }
612    }
613
614    /**
615     * Pre-HC, we didn't have a way to determine whether an activity was
616     * being stopped for a config change or not until we saw
617     * onRetainNonConfigurationInstance() called after onStop().  However
618     * we need to know this, to know whether to retain fragments.  This will
619     * tell us what we need to know.
620     */
621    void onReallyStop() {
622        if (mLoadersStarted) {
623            mLoadersStarted = false;
624            if (mLoaderManager != null) {
625                if (!mRetaining) {
626                    mLoaderManager.doStop();
627                } else {
628                    mLoaderManager.doRetain();
629                }
630            }
631        }
632
633        mFragments.dispatchReallyStop();
634    }
635
636    // ------------------------------------------------------------------------
637    // FRAGMENT SUPPORT
638    // ------------------------------------------------------------------------
639
640    /**
641     * Called when a fragment is attached to the activity.
642     */
643    public void onAttachFragment(Fragment fragment) {
644    }
645
646    /**
647     * Return the FragmentManager for interacting with fragments associated
648     * with this activity.
649     */
650    public FragmentManager getSupportFragmentManager() {
651        return mFragments;
652    }
653
654    /**
655     * Modifies the standard behavior to allow results to be delivered to fragments.
656     * This imposes a restriction that requestCode be <= 0xffff.
657     */
658    @Override
659    public void startActivityForResult(Intent intent, int requestCode) {
660        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
661            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
662        }
663        super.startActivityForResult(intent, requestCode);
664    }
665
666    /**
667     * Called by Fragment.startActivityForResult() to implement its behavior.
668     */
669    public void startActivityFromFragment(Fragment fragment, Intent intent,
670            int requestCode) {
671        if (requestCode == -1) {
672            super.startActivityForResult(intent, -1);
673            return;
674        }
675        if ((requestCode&0xffff0000) != 0) {
676            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
677        }
678        super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
679    }
680
681    void invalidateSupportFragmentIndex(int index) {
682        //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
683        if (mAllLoaderManagers != null) {
684            LoaderManagerImpl lm = mAllLoaderManagers.get(index);
685            if (lm != null && !lm.mRetaining) {
686                lm.doDestroy();
687                mAllLoaderManagers.remove(index);
688            }
689        }
690    }
691
692    // ------------------------------------------------------------------------
693    // LOADER SUPPORT
694    // ------------------------------------------------------------------------
695
696    /**
697     * Return the LoaderManager for this fragment, creating it if needed.
698     */
699    public LoaderManager getSupportLoaderManager() {
700        if (mLoaderManager != null) {
701            return mLoaderManager;
702        }
703        mCheckedForLoaderManager = true;
704        mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
705        return mLoaderManager;
706    }
707
708    LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
709        if (mAllLoaderManagers == null) {
710            mAllLoaderManagers = new HCSparseArray<LoaderManagerImpl>();
711        }
712        LoaderManagerImpl lm = mAllLoaderManagers.get(index);
713        if (lm == null) {
714            if (create) {
715                lm = new LoaderManagerImpl(this, started);
716                mAllLoaderManagers.put(index, lm);
717            }
718        } else {
719            lm.updateActivity(this);
720        }
721        return lm;
722    }
723}
724