FragmentActivity.java revision ea2c91b0198855073983b4a8437aa71cbd83872f
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
99    boolean mOptionsMenuInvalidated;
100
101    boolean mCheckedForLoaderManager;
102    boolean mLoadersStarted;
103    HCSparseArray<LoaderManagerImpl> mAllLoaderManagers;
104    LoaderManagerImpl mLoaderManager;
105
106    static final class NonConfigurationInstances {
107        Object activity;
108        HashMap<String, Object> children;
109        ArrayList<Fragment> fragments;
110        HCSparseArray<LoaderManagerImpl> loaders;
111    }
112
113    static class FragmentTag {
114        public static final int[] Fragment = {
115            0x01010003, 0x010100d0, 0x010100d1
116        };
117        public static final int Fragment_id = 1;
118        public static final int Fragment_name = 0;
119        public static final int Fragment_tag = 2;
120    }
121
122    // ------------------------------------------------------------------------
123    // HOOKS INTO ACTIVITY
124    // ------------------------------------------------------------------------
125
126    /**
127     * Dispatch incoming result to the correct fragment.
128     */
129    @Override
130    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
131        int index = requestCode>>16;
132        if (index != 0) {
133            index--;
134            if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
135                Log.w(TAG, "Activity result fragment index out of range: 0x"
136                        + Integer.toHexString(requestCode));
137                return;
138            }
139            Fragment frag = mFragments.mActive.get(index);
140            if (frag == null) {
141                Log.w(TAG, "Activity result no fragment exists for index: 0x"
142                        + Integer.toHexString(requestCode));
143            }
144            frag.onActivityResult(requestCode&0xffff, resultCode, data);
145            return;
146        }
147
148        super.onActivityResult(requestCode, resultCode, data);
149    }
150
151    /**
152     * Take care of popping the fragment back stack or finishing the activity
153     * as appropriate.
154     */
155    public void onBackPressed() {
156        if (!mFragments.popBackStackImmediate()) {
157            finish();
158        }
159    }
160
161    /**
162     * Dispatch configuration change to all fragments.
163     */
164    @Override
165    public void onConfigurationChanged(Configuration newConfig) {
166        super.onConfigurationChanged(newConfig);
167        mFragments.dispatchConfigurationChanged(newConfig);
168    }
169
170    /**
171     * Perform initialization of all fragments and loaders.
172     */
173    @Override
174    protected void onCreate(Bundle savedInstanceState) {
175        mFragments.attachActivity(this);
176        // Old versions of the platform didn't do this!
177        if (getLayoutInflater().getFactory() == null) {
178            getLayoutInflater().setFactory(this);
179        }
180
181        super.onCreate(savedInstanceState);
182
183        NonConfigurationInstances nc = (NonConfigurationInstances)
184                getLastNonConfigurationInstance();
185        if (nc != null) {
186            mAllLoaderManagers = nc.loaders;
187        }
188        if (savedInstanceState != null) {
189            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
190            mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
191        }
192        mFragments.dispatchCreate();
193    }
194
195    /**
196     * Dispatch to Fragment.onCreateOptionsMenu().
197     */
198    @Override
199    public boolean onCreatePanelMenu(int featureId, Menu menu) {
200        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
201            boolean show = super.onCreatePanelMenu(featureId, menu);
202            show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
203            if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
204                return show;
205            }
206            // Prior to Honeycomb, the framework can't invalidate the options
207            // menu, so we must always say we have one in case the app later
208            // invalidates it and needs to have it shown.
209            return true;
210        }
211        return super.onCreatePanelMenu(featureId, menu);
212    }
213
214    /**
215     * Add support for inflating the &lt;fragment> tag.
216     */
217    @Override
218    public View onCreateView(String name, Context context, AttributeSet attrs) {
219        if (!"fragment".equals(name)) {
220            return super.onCreateView(name, context, attrs);
221        }
222
223        String fname = attrs.getAttributeValue(null, "class");
224        TypedArray a =  context.obtainStyledAttributes(attrs, FragmentTag.Fragment);
225        if (fname == null) {
226            fname = a.getString(FragmentTag.Fragment_name);
227        }
228        int id = a.getResourceId(FragmentTag.Fragment_id, View.NO_ID);
229        String tag = a.getString(FragmentTag.Fragment_tag);
230        a.recycle();
231
232        View parent = null; // NOTE: no way to get parent pre-Honeycomb.
233        int containerId = parent != null ? parent.getId() : 0;
234        if (containerId == View.NO_ID && id == View.NO_ID && tag == null) {
235            throw new IllegalArgumentException(attrs.getPositionDescription()
236                    + ": Must specify unique android:id, android:tag, or have a parent with an id for " + fname);
237        }
238
239        // If we restored from a previous state, we may already have
240        // instantiated this fragment from the state and should use
241        // that instance instead of making a new one.
242        Fragment fragment = id != View.NO_ID ? mFragments.findFragmentById(id) : null;
243        if (fragment == null && tag != null) {
244            fragment = mFragments.findFragmentByTag(tag);
245        }
246        if (fragment == null && containerId != View.NO_ID) {
247            fragment = mFragments.findFragmentById(containerId);
248        }
249
250        if (FragmentManagerImpl.DEBUG) Log.v(TAG, "onCreateView: id=0x"
251                + Integer.toHexString(id) + " fname=" + fname
252                + " existing=" + fragment);
253        if (fragment == null) {
254            fragment = Fragment.instantiate(this, fname);
255            fragment.mFromLayout = true;
256            fragment.mFragmentId = id != 0 ? id : containerId;
257            fragment.mContainerId = containerId;
258            fragment.mTag = tag;
259            fragment.mInLayout = true;
260            fragment.mImmediateActivity = this;
261            fragment.mFragmentManager = mFragments;
262            fragment.onInflate(this, attrs, fragment.mSavedFragmentState);
263            mFragments.addFragment(fragment, true);
264
265        } else if (fragment.mInLayout) {
266            // A fragment already exists and it is not one we restored from
267            // previous state.
268            throw new IllegalArgumentException(attrs.getPositionDescription()
269                    + ": Duplicate id 0x" + Integer.toHexString(id)
270                    + ", tag " + tag + ", or parent id 0x" + Integer.toHexString(containerId)
271                    + " with another fragment for " + fname);
272        } else {
273            // This fragment was retained from a previous instance; get it
274            // going now.
275            fragment.mInLayout = true;
276            fragment.mImmediateActivity = this;
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!
431     */
432    @Override
433    public final Object onRetainNonConfigurationInstance() {
434        if (mStopped) {
435            doReallyStop(true);
436        }
437
438        ArrayList<Fragment> fragments = mFragments.retainNonConfig();
439        boolean retainLoaders = false;
440        if (mAllLoaderManagers != null) {
441            // prune out any loader managers that were already stopped and so
442            // have nothing useful to retain.
443            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
444                LoaderManagerImpl lm = mAllLoaderManagers.valueAt(i);
445                if (lm.mRetaining) {
446                    retainLoaders = true;
447                } else {
448                    lm.doDestroy();
449                    mAllLoaderManagers.removeAt(i);
450                }
451            }
452        }
453        if (fragments == null && !retainLoaders) {
454            return null;
455        }
456
457        NonConfigurationInstances nci = new NonConfigurationInstances();
458        nci.activity = null;
459        nci.children = null;
460        nci.fragments = fragments;
461        nci.loaders = mAllLoaderManagers;
462        return nci;
463    }
464
465    /**
466     * Save all appropriate fragment state.
467     */
468    @Override
469    protected void onSaveInstanceState(Bundle outState) {
470        super.onSaveInstanceState(outState);
471        Parcelable p = mFragments.saveAllState();
472        if (p != null) {
473            outState.putParcelable(FRAGMENTS_TAG, p);
474        }
475    }
476
477    /**
478     * Dispatch onStart() to all fragments.  Ensure any created loaders are
479     * now started.
480     */
481    @Override
482    protected void onStart() {
483        super.onStart();
484
485        mStopped = false;
486        mHandler.removeMessages(MSG_REALLY_STOPPED);
487
488        if (!mCreated) {
489            mCreated = true;
490            mFragments.dispatchActivityCreated();
491        }
492
493        mFragments.noteStateNotSaved();
494        mFragments.execPendingActions();
495
496        if (!mLoadersStarted) {
497            mLoadersStarted = true;
498            if (mLoaderManager != null) {
499                mLoaderManager.doStart();
500            } else if (!mCheckedForLoaderManager) {
501                mLoaderManager = getLoaderManager(-1, mLoadersStarted, false);
502            }
503            mCheckedForLoaderManager = true;
504        }
505        // NOTE: HC onStart goes here.
506
507        mFragments.dispatchStart();
508        if (mAllLoaderManagers != null) {
509            for (int i=mAllLoaderManagers.size()-1; i>=0; i--) {
510                mAllLoaderManagers.valueAt(i).finishRetain();
511            }
512        }
513    }
514
515    /**
516     * Dispatch onStop() to all fragments.  Ensure all loaders are stopped.
517     */
518    @Override
519    protected void onStop() {
520        super.onStop();
521
522        mStopped = true;
523        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
524
525        mFragments.dispatchStop();
526    }
527
528    // ------------------------------------------------------------------------
529    // NEW METHODS
530    // ------------------------------------------------------------------------
531
532    void supportInvalidateOptionsMenu() {
533        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
534            // If we are running on HC or greater, we can use the framework
535            // API to invalidate the options menu.
536            ActivityCompatHoneycomb.invalidateOptionsMenu(this);
537            return;
538        }
539
540        // Whoops, older platform...  we'll use a hack, to manually rebuild
541        // the options menu the next time it is prepared.
542        mOptionsMenuInvalidated = true;
543    }
544
545    /**
546     * Print the Activity's state into the given stream.  This gets invoked if
547     * you run "adb shell dumpsys activity <activity_component_name>".
548     *
549     * @param prefix Desired prefix to prepend at each line of output.
550     * @param fd The raw file descriptor that the dump is being sent to.
551     * @param writer The PrintWriter to which you should dump your state.  This will be
552     * closed for you after you return.
553     * @param args additional arguments to the dump request.
554     */
555    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
556        if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
557            // XXX This can only work if we can call the super-class impl. :/
558            //ActivityCompatHoneycomb.dump(this, prefix, fd, writer, args);
559        }
560        writer.print(prefix); writer.print("Local FragmentActivity ");
561                writer.print(Integer.toHexString(System.identityHashCode(this)));
562                writer.println(" State:");
563        String innerPrefix = prefix + "  ";
564        writer.print(innerPrefix); writer.print("mCreated=");
565                writer.print(mCreated); writer.print("mResumed=");
566                writer.print(mResumed); writer.print(" mStopped=");
567                writer.print(mStopped); writer.print(" mReallyStopped=");
568                writer.println(mReallyStopped);
569        writer.print(innerPrefix); writer.print("mLoadersStarted=");
570                writer.println(mLoadersStarted);
571        if (mLoaderManager != null) {
572            writer.print(prefix); writer.print("Loader Manager ");
573                    writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
574                    writer.println(":");
575            mLoaderManager.dump(prefix + "  ", fd, writer, args);
576        }
577        mFragments.dump(prefix, fd, writer, args);
578    }
579
580    void doReallyStop(boolean retaining) {
581        if (!mReallyStopped) {
582            mReallyStopped = true;
583            mHandler.removeMessages(MSG_REALLY_STOPPED);
584            onReallyStop(retaining);
585        }
586    }
587
588    /**
589     * Pre-HC, we didn't have a way to determine whether an activity was
590     * being stopped for a config change or not until we saw
591     * onRetainNonConfigurationInstance() called after onStop().  However
592     * we need to know this, to know whether to retain fragments.  This will
593     * tell us what we need to know.
594     */
595    void onReallyStop(boolean retaining) {
596        if (mLoadersStarted) {
597            mLoadersStarted = false;
598            if (mLoaderManager != null) {
599                if (!retaining) {
600                    mLoaderManager.doStop();
601                } else {
602                    mLoaderManager.doRetain();
603                }
604            }
605        }
606
607        mFragments.dispatchReallyStop(retaining);
608    }
609
610    // ------------------------------------------------------------------------
611    // FRAGMENT SUPPORT
612    // ------------------------------------------------------------------------
613
614    /**
615     * Called when a fragment is attached to the activity.
616     */
617    public void onAttachFragment(Fragment fragment) {
618    }
619
620    /**
621     * Return the FragmentManager for interacting with fragments associated
622     * with this activity.
623     */
624    public FragmentManager getSupportFragmentManager() {
625        return mFragments;
626    }
627
628    /**
629     * Modifies the standard behavior to allow results to be delivered to fragments.
630     * This imposes a restriction that requestCode be <= 0xffff.
631     */
632    @Override
633    public void startActivityForResult(Intent intent, int requestCode) {
634        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
635            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
636        }
637        super.startActivityForResult(intent, requestCode);
638    }
639
640    /**
641     * Called by Fragment.startActivityForResult() to implement its behavior.
642     */
643    public void startActivityFromFragment(Fragment fragment, Intent intent,
644            int requestCode) {
645        if (requestCode == -1) {
646            super.startActivityForResult(intent, -1);
647            return;
648        }
649        if ((requestCode&0xffff0000) != 0) {
650            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
651        }
652        super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
653    }
654
655    void invalidateSupportFragmentIndex(int index) {
656        //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
657        if (mAllLoaderManagers != null) {
658            LoaderManagerImpl lm = mAllLoaderManagers.get(index);
659            if (lm != null) {
660                lm.doDestroy();
661            }
662            mAllLoaderManagers.remove(index);
663        }
664    }
665
666    // ------------------------------------------------------------------------
667    // LOADER SUPPORT
668    // ------------------------------------------------------------------------
669
670    /**
671     * Return the LoaderManager for this fragment, creating it if needed.
672     */
673    public LoaderManager getSupportLoaderManager() {
674        if (mLoaderManager != null) {
675            return mLoaderManager;
676        }
677        mCheckedForLoaderManager = true;
678        mLoaderManager = getLoaderManager(-1, mLoadersStarted, true);
679        return mLoaderManager;
680    }
681
682    LoaderManagerImpl getLoaderManager(int index, boolean started, boolean create) {
683        if (mAllLoaderManagers == null) {
684            mAllLoaderManagers = new HCSparseArray<LoaderManagerImpl>();
685        }
686        LoaderManagerImpl lm = mAllLoaderManagers.get(index);
687        if (lm == null) {
688            if (create) {
689                lm = new LoaderManagerImpl(this, started);
690                mAllLoaderManagers.put(index, lm);
691            }
692        } else {
693            lm.updateActivity(this);
694        }
695        return lm;
696    }
697}
698