FragmentActivity.java revision e1e957f536c20ebe2a7e6c417ccb2fd8f7fa845b
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.os.Bundle;
25import android.os.Handler;
26import android.os.Message;
27import android.os.Parcelable;
28import android.support.annotation.NonNull;
29import android.support.annotation.Nullable;
30import android.support.v4.util.SimpleArrayMap;
31import android.util.AttributeSet;
32import android.util.Log;
33import android.view.KeyEvent;
34import android.view.LayoutInflater;
35import android.view.Menu;
36import android.view.MenuItem;
37import android.view.View;
38import android.view.ViewGroup;
39import android.view.Window;
40
41import java.io.FileDescriptor;
42import java.io.PrintWriter;
43import java.util.ArrayList;
44import java.util.List;
45
46/**
47 * Base class for activities that want to use the support-based
48 * {@link android.support.v4.app.Fragment} and
49 * {@link android.support.v4.content.Loader} APIs.
50 *
51 * <p>When using this class as opposed to new platform's built-in fragment
52 * and loader support, you must use the {@link #getSupportFragmentManager()}
53 * and {@link #getSupportLoaderManager()} methods respectively to access
54 * those features.
55 *
56 * <p class="note"><strong>Note:</strong> If you want to implement an activity that includes
57 * an <a href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>, you should instead use
58 * the {@link android.support.v7.app.ActionBarActivity} class, which is a subclass of this one,
59 * so allows you to use {@link android.support.v4.app.Fragment} APIs on API level 7 and higher.</p>
60 *
61 * <p>Known limitations:</p>
62 * <ul>
63 * <li> <p>When using the <code>&lt;fragment></code> tag, this implementation can not
64 * use the parent view's ID as the new fragment's ID.  You must explicitly
65 * specify an ID (or tag) in the <code>&lt;fragment></code>.</p>
66 * <li> <p>Prior to Honeycomb (3.0), an activity's state was saved before pausing.
67 * Fragments are a significant amount of new state, and dynamic enough that one
68 * often wants them to change between pausing and stopping.  These classes
69 * throw an exception if you try to change the fragment state after it has been
70 * saved, to avoid accidental loss of UI state.  However this is too restrictive
71 * prior to Honeycomb, where the state is saved before pausing.  To address this,
72 * when running on platforms prior to Honeycomb an exception will not be thrown
73 * if you change fragments between the state save and the activity being stopped.
74 * This means that in some cases if the activity is restored from its last saved
75 * state, this may be a snapshot slightly before what the user last saw.</p>
76 * </ul>
77 */
78public class FragmentActivity extends BaseFragmentActivityHoneycomb implements
79        ActivityCompat.OnRequestPermissionsResultCallback,
80        ActivityCompatApi23.RequestPermissionsRequestCodeValidator {
81    private static final String TAG = "FragmentActivity";
82
83    static final String FRAGMENTS_TAG = "android:support:fragments";
84
85    // This is the SDK API version of Honeycomb (3.0).
86    private static final int HONEYCOMB = 11;
87
88    static final int MSG_REALLY_STOPPED = 1;
89    static final int MSG_RESUME_PENDING = 2;
90
91    final Handler mHandler = new Handler() {
92        @Override
93        public void handleMessage(Message msg) {
94            switch (msg.what) {
95                case MSG_REALLY_STOPPED:
96                    if (mStopped) {
97                        doReallyStop(false);
98                    }
99                    break;
100                case MSG_RESUME_PENDING:
101                    onResumeFragments();
102                    mFragments.execPendingActions();
103                    break;
104                default:
105                    super.handleMessage(msg);
106            }
107        }
108
109    };
110    final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
111
112    boolean mCreated;
113    boolean mResumed;
114    boolean mStopped;
115    boolean mReallyStopped;
116    boolean mRetaining;
117
118    boolean mOptionsMenuInvalidated;
119    boolean mRequestedPermissionsFromFragment;
120
121    static final class NonConfigurationInstances {
122        Object custom;
123        List<Fragment> fragments;
124        SimpleArrayMap<String, LoaderManager> loaders;
125    }
126
127    // ------------------------------------------------------------------------
128    // HOOKS INTO ACTIVITY
129    // ------------------------------------------------------------------------
130
131    /**
132     * Dispatch incoming result to the correct fragment.
133     */
134    @Override
135    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
136        mFragments.noteStateNotSaved();
137        int index = requestCode>>16;
138        if (index != 0) {
139            index--;
140            final int activeFragmentsCount = mFragments.getActiveFragmentsCount();
141            if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) {
142                Log.w(TAG, "Activity result fragment index out of range: 0x"
143                        + Integer.toHexString(requestCode));
144                return;
145            }
146            final List<Fragment> activeFragments =
147                    mFragments.getActiveFragments(new ArrayList<Fragment>(activeFragmentsCount));
148            Fragment frag = activeFragments.get(index);
149            if (frag == null) {
150                Log.w(TAG, "Activity result no fragment exists for index: 0x"
151                        + Integer.toHexString(requestCode));
152            } else {
153                frag.onActivityResult(requestCode&0xffff, resultCode, data);
154            }
155            return;
156        }
157
158        super.onActivityResult(requestCode, resultCode, data);
159    }
160
161    /**
162     * Take care of popping the fragment back stack or finishing the activity
163     * as appropriate.
164     */
165    public void onBackPressed() {
166        if (!mFragments.getSupportFragmentManager().popBackStackImmediate()) {
167            supportFinishAfterTransition();
168        }
169    }
170
171    /**
172     * Reverses the Activity Scene entry Transition and triggers the calling Activity
173     * to reverse its exit Transition. When the exit Transition completes,
174     * {@link #finish()} is called. If no entry Transition was used, finish() is called
175     * immediately and the Activity exit Transition is run.
176     *
177     * <p>On Android 4.4 or lower, this method only finishes the Activity with no
178     * special exit transition.</p>
179     */
180    public void supportFinishAfterTransition() {
181        ActivityCompat.finishAfterTransition(this);
182    }
183
184    /**
185     * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
186     * android.view.View, String)} was used to start an Activity, <var>callback</var>
187     * will be called to handle shared elements on the <i>launched</i> Activity. This requires
188     * {@link Window#FEATURE_CONTENT_TRANSITIONS}.
189     *
190     * @param callback Used to manipulate shared element transitions on the launched Activity.
191     */
192    public void setEnterSharedElementCallback(SharedElementCallback callback) {
193        ActivityCompat.setEnterSharedElementCallback(this, callback);
194    }
195
196    /**
197     * When {@link android.app.ActivityOptions#makeSceneTransitionAnimation(Activity,
198     * android.view.View, String)} was used to start an Activity, <var>listener</var>
199     * will be called to handle shared elements on the <i>launching</i> Activity. Most
200     * calls will only come when returning from the started Activity.
201     * This requires {@link Window#FEATURE_CONTENT_TRANSITIONS}.
202     *
203     * @param listener Used to manipulate shared element transitions on the launching Activity.
204     */
205    public void setExitSharedElementCallback(SharedElementCallback listener) {
206        ActivityCompat.setExitSharedElementCallback(this, listener);
207    }
208
209    /**
210     * Support library version of {@link android.app.Activity#postponeEnterTransition()} that works
211     * only on API 21 and later.
212     */
213    public void supportPostponeEnterTransition() {
214        ActivityCompat.postponeEnterTransition(this);
215    }
216
217    /**
218     * Support library version of {@link android.app.Activity#startPostponedEnterTransition()}
219     * that only works with API 21 and later.
220     */
221    public void supportStartPostponedEnterTransition() {
222        ActivityCompat.startPostponedEnterTransition(this);
223    }
224
225    /**
226     * Dispatch configuration change to all fragments.
227     */
228    @Override
229    public void onConfigurationChanged(Configuration newConfig) {
230        super.onConfigurationChanged(newConfig);
231        mFragments.dispatchConfigurationChanged(newConfig);
232    }
233
234    /**
235     * Perform initialization of all fragments and loaders.
236     */
237    @SuppressWarnings("deprecation")
238    @Override
239    protected void onCreate(@Nullable Bundle savedInstanceState) {
240        mFragments.attachHost(null /*parent*/);
241
242        super.onCreate(savedInstanceState);
243
244        NonConfigurationInstances nc =
245                (NonConfigurationInstances) getLastNonConfigurationInstance();
246        if (nc != null) {
247            mFragments.restoreLoaderNonConfig(nc.loaders);
248        }
249        if (savedInstanceState != null) {
250            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
251            mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
252        }
253        mFragments.dispatchCreate();
254    }
255
256    /**
257     * Dispatch to Fragment.onCreateOptionsMenu().
258     */
259    @Override
260    public boolean onCreatePanelMenu(int featureId, Menu menu) {
261        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
262            boolean show = super.onCreatePanelMenu(featureId, menu);
263            show |= mFragments.dispatchCreateOptionsMenu(menu, getMenuInflater());
264            if (android.os.Build.VERSION.SDK_INT >= HONEYCOMB) {
265                return show;
266            }
267            // Prior to Honeycomb, the framework can't invalidate the options
268            // menu, so we must always say we have one in case the app later
269            // invalidates it and needs to have it shown.
270            return true;
271        }
272        return super.onCreatePanelMenu(featureId, menu);
273    }
274
275    @Override
276    final View dispatchFragmentsOnCreateView(View parent, String name, Context context,
277            AttributeSet attrs) {
278        return mFragments.onCreateView(parent, name, context, attrs);
279    }
280
281    /**
282     * Destroy all fragments and loaders.
283     */
284    @Override
285    protected void onDestroy() {
286        super.onDestroy();
287
288        doReallyStop(false);
289
290        mFragments.dispatchDestroy();
291        mFragments.doLoaderDestroy();
292    }
293
294    /**
295     * Take care of calling onBackPressed() for pre-Eclair platforms.
296     */
297    @Override
298    public boolean onKeyDown(int keyCode, KeyEvent event) {
299        if (android.os.Build.VERSION.SDK_INT < 5 /* ECLAIR */
300                && keyCode == KeyEvent.KEYCODE_BACK
301                && event.getRepeatCount() == 0) {
302            // Take care of calling this method on earlier versions of
303            // the platform where it doesn't exist.
304            onBackPressed();
305            return true;
306        }
307
308        return super.onKeyDown(keyCode, event);
309    }
310
311    /**
312     * Dispatch onLowMemory() to all fragments.
313     */
314    @Override
315    public void onLowMemory() {
316        super.onLowMemory();
317        mFragments.dispatchLowMemory();
318    }
319
320    /**
321     * Dispatch context and options menu to fragments.
322     */
323    @Override
324    public boolean onMenuItemSelected(int featureId, MenuItem item) {
325        if (super.onMenuItemSelected(featureId, item)) {
326            return true;
327        }
328
329        switch (featureId) {
330            case Window.FEATURE_OPTIONS_PANEL:
331                return mFragments.dispatchOptionsItemSelected(item);
332
333            case Window.FEATURE_CONTEXT_MENU:
334                return mFragments.dispatchContextItemSelected(item);
335
336            default:
337                return false;
338        }
339    }
340
341    /**
342     * Call onOptionsMenuClosed() on fragments.
343     */
344    @Override
345    public void onPanelClosed(int featureId, Menu menu) {
346        switch (featureId) {
347            case Window.FEATURE_OPTIONS_PANEL:
348                mFragments.dispatchOptionsMenuClosed(menu);
349                break;
350        }
351        super.onPanelClosed(featureId, menu);
352    }
353
354    /**
355     * Dispatch onPause() to fragments.
356     */
357    @Override
358    protected void onPause() {
359        super.onPause();
360        mResumed = false;
361        if (mHandler.hasMessages(MSG_RESUME_PENDING)) {
362            mHandler.removeMessages(MSG_RESUME_PENDING);
363            onResumeFragments();
364        }
365        mFragments.dispatchPause();
366    }
367
368    /**
369     * Handle onNewIntent() to inform the fragment manager that the
370     * state is not saved.  If you are handling new intents and may be
371     * making changes to the fragment state, you want to be sure to call
372     * through to the super-class here first.  Otherwise, if your state
373     * is saved but the activity is not stopped, you could get an
374     * onNewIntent() call which happens before onResume() and trying to
375     * perform fragment operations at that point will throw IllegalStateException
376     * because the fragment manager thinks the state is still saved.
377     */
378    @Override
379    protected void onNewIntent(Intent intent) {
380        super.onNewIntent(intent);
381        mFragments.noteStateNotSaved();
382    }
383
384    /**
385     * Dispatch onResume() to fragments.  Note that for better inter-operation
386     * with older versions of the platform, at the point of this call the
387     * fragments attached to the activity are <em>not</em> resumed.  This means
388     * that in some cases the previous state may still be saved, not allowing
389     * fragment transactions that modify the state.  To correctly interact
390     * with fragments in their proper state, you should instead override
391     * {@link #onResumeFragments()}.
392     */
393    @Override
394    protected void onResume() {
395        super.onResume();
396        mHandler.sendEmptyMessage(MSG_RESUME_PENDING);
397        mResumed = true;
398        mFragments.execPendingActions();
399    }
400
401    /**
402     * Dispatch onResume() to fragments.
403     */
404    @Override
405    protected void onPostResume() {
406        super.onPostResume();
407        mHandler.removeMessages(MSG_RESUME_PENDING);
408        onResumeFragments();
409        mFragments.execPendingActions();
410    }
411
412    /**
413     * This is the fragment-orientated version of {@link #onResume()} that you
414     * can override to perform operations in the Activity at the same point
415     * where its fragments are resumed.  Be sure to always call through to
416     * the super-class.
417     */
418    protected void onResumeFragments() {
419        mFragments.dispatchResume();
420    }
421
422    /**
423     * Dispatch onPrepareOptionsMenu() to fragments.
424     */
425    @Override
426    public boolean onPreparePanel(int featureId, View view, Menu menu) {
427        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
428            if (mOptionsMenuInvalidated) {
429                mOptionsMenuInvalidated = false;
430                menu.clear();
431                onCreatePanelMenu(featureId, menu);
432            }
433            boolean goforit = onPrepareOptionsPanel(view, menu);
434            goforit |= mFragments.dispatchPrepareOptionsMenu(menu);
435            return goforit;
436        }
437        return super.onPreparePanel(featureId, view, menu);
438    }
439
440    /**
441     * @hide
442     */
443    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
444        return super.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, view, menu);
445    }
446
447    /**
448     * Retain all appropriate fragment and loader state.  You can NOT
449     * override this yourself!  Use {@link #onRetainCustomNonConfigurationInstance()}
450     * if you want to retain your own state.
451     */
452    @Override
453    public final Object onRetainNonConfigurationInstance() {
454        if (mStopped) {
455            doReallyStop(true);
456        }
457
458        Object custom = onRetainCustomNonConfigurationInstance();
459
460        List<Fragment> fragments = mFragments.retainNonConfig();
461        SimpleArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
462
463        if (fragments == null && loaders == null && custom == null) {
464            return null;
465        }
466
467        NonConfigurationInstances nci = new NonConfigurationInstances();
468        nci.custom = custom;
469        nci.fragments = fragments;
470        nci.loaders = loaders;
471        return nci;
472    }
473
474    /**
475     * Save all appropriate fragment state.
476     */
477    @Override
478    protected void onSaveInstanceState(Bundle outState) {
479        super.onSaveInstanceState(outState);
480        Parcelable p = mFragments.saveAllState();
481        if (p != null) {
482            outState.putParcelable(FRAGMENTS_TAG, p);
483        }
484    }
485
486    /**
487     * Dispatch onStart() to all fragments.  Ensure any created loaders are
488     * now started.
489     */
490    @Override
491    protected void onStart() {
492        super.onStart();
493
494        mStopped = false;
495        mReallyStopped = false;
496        mHandler.removeMessages(MSG_REALLY_STOPPED);
497
498        if (!mCreated) {
499            mCreated = true;
500            mFragments.dispatchActivityCreated();
501        }
502
503        mFragments.noteStateNotSaved();
504        mFragments.execPendingActions();
505
506        mFragments.doLoaderStart();
507
508        // NOTE: HC onStart goes here.
509
510        mFragments.dispatchStart();
511        mFragments.reportLoaderStart();
512    }
513
514    /**
515     * Dispatch onStop() to all fragments.  Ensure all loaders are stopped.
516     */
517    @Override
518    protected void onStop() {
519        super.onStop();
520
521        mStopped = true;
522        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);
523
524        mFragments.dispatchStop();
525    }
526
527    // ------------------------------------------------------------------------
528    // NEW METHODS
529    // ------------------------------------------------------------------------
530
531    /**
532     * Use this instead of {@link #onRetainNonConfigurationInstance()}.
533     * Retrieve later with {@link #getLastCustomNonConfigurationInstance()}.
534     */
535    public Object onRetainCustomNonConfigurationInstance() {
536        return null;
537    }
538
539    /**
540     * Return the value previously returned from
541     * {@link #onRetainCustomNonConfigurationInstance()}.
542     */
543    @SuppressWarnings("deprecation")
544    public Object getLastCustomNonConfigurationInstance() {
545        NonConfigurationInstances nc = (NonConfigurationInstances)
546                getLastNonConfigurationInstance();
547        return nc != null ? nc.custom : null;
548    }
549
550    /**
551     * Support library version of {@link Activity#invalidateOptionsMenu}.
552     *
553     * <p>Invalidate the activity's options menu. This will cause relevant presentations
554     * of the menu to fully update via calls to onCreateOptionsMenu and
555     * onPrepareOptionsMenu the next time the menu is requested.
556     */
557    public 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        mFragments.dumpLoaders(innerPrefix, fd, writer, args);
595        mFragments.getSupportFragmentManager().dump(prefix, fd, writer, args);
596        writer.print(prefix); writer.println("View Hierarchy:");
597        dumpViewHierarchy(prefix + "  ", writer, getWindow().getDecorView());
598    }
599
600    private static String viewToString(View view) {
601        StringBuilder out = new StringBuilder(128);
602        out.append(view.getClass().getName());
603        out.append('{');
604        out.append(Integer.toHexString(System.identityHashCode(view)));
605        out.append(' ');
606        switch (view.getVisibility()) {
607            case View.VISIBLE: out.append('V'); break;
608            case View.INVISIBLE: out.append('I'); break;
609            case View.GONE: out.append('G'); break;
610            default: out.append('.'); break;
611        }
612        out.append(view.isFocusable() ? 'F' : '.');
613        out.append(view.isEnabled() ? 'E' : '.');
614        out.append(view.willNotDraw() ? '.' : 'D');
615        out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
616        out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
617        out.append(view.isClickable() ? 'C' : '.');
618        out.append(view.isLongClickable() ? 'L' : '.');
619        out.append(' ');
620        out.append(view.isFocused() ? 'F' : '.');
621        out.append(view.isSelected() ? 'S' : '.');
622        out.append(view.isPressed() ? 'P' : '.');
623        out.append(' ');
624        out.append(view.getLeft());
625        out.append(',');
626        out.append(view.getTop());
627        out.append('-');
628        out.append(view.getRight());
629        out.append(',');
630        out.append(view.getBottom());
631        final int id = view.getId();
632        if (id != View.NO_ID) {
633            out.append(" #");
634            out.append(Integer.toHexString(id));
635            final Resources r = view.getResources();
636            if (id != 0 && r != null) {
637                try {
638                    String pkgname;
639                    switch (id&0xff000000) {
640                        case 0x7f000000:
641                            pkgname="app";
642                            break;
643                        case 0x01000000:
644                            pkgname="android";
645                            break;
646                        default:
647                            pkgname = r.getResourcePackageName(id);
648                            break;
649                    }
650                    String typename = r.getResourceTypeName(id);
651                    String entryname = r.getResourceEntryName(id);
652                    out.append(" ");
653                    out.append(pkgname);
654                    out.append(":");
655                    out.append(typename);
656                    out.append("/");
657                    out.append(entryname);
658                } catch (Resources.NotFoundException e) {
659                }
660            }
661        }
662        out.append("}");
663        return out.toString();
664    }
665
666    private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
667        writer.print(prefix);
668        if (view == null) {
669            writer.println("null");
670            return;
671        }
672        writer.println(viewToString(view));
673        if (!(view instanceof ViewGroup)) {
674            return;
675        }
676        ViewGroup grp = (ViewGroup)view;
677        final int N = grp.getChildCount();
678        if (N <= 0) {
679            return;
680        }
681        prefix = prefix + "  ";
682        for (int i=0; i<N; i++) {
683            dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
684        }
685    }
686
687    void doReallyStop(boolean retaining) {
688        if (!mReallyStopped) {
689            mReallyStopped = true;
690            mRetaining = retaining;
691            mHandler.removeMessages(MSG_REALLY_STOPPED);
692            onReallyStop();
693        }
694    }
695
696    /**
697     * Pre-HC, we didn't have a way to determine whether an activity was
698     * being stopped for a config change or not until we saw
699     * onRetainNonConfigurationInstance() called after onStop().  However
700     * we need to know this, to know whether to retain fragments.  This will
701     * tell us what we need to know.
702     */
703    void onReallyStop() {
704        mFragments.doLoaderStop(mRetaining);
705
706        mFragments.dispatchReallyStop();
707    }
708
709    // ------------------------------------------------------------------------
710    // FRAGMENT SUPPORT
711    // ------------------------------------------------------------------------
712
713    /**
714     * Called when a fragment is attached to the activity.
715     */
716    @SuppressWarnings("unused")
717    public void onAttachFragment(Fragment fragment) {
718    }
719
720    /**
721     * Return the FragmentManager for interacting with fragments associated
722     * with this activity.
723     */
724    public FragmentManager getSupportFragmentManager() {
725        return mFragments.getSupportFragmentManager();
726    }
727
728    public LoaderManager getSupportLoaderManager() {
729        return mFragments.getSupportLoaderManager();
730    }
731
732    /**
733     * Modifies the standard behavior to allow results to be delivered to fragments.
734     * This imposes a restriction that requestCode be <= 0xffff.
735     */
736    @Override
737    public void startActivityForResult(Intent intent, int requestCode) {
738        if (requestCode != -1 && (requestCode&0xffff0000) != 0) {
739            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
740        }
741        super.startActivityForResult(intent, requestCode);
742    }
743
744    @Override
745    public final void validateRequestPermissionsRequestCode(int requestCode) {
746        // We use 8 bits of the request code to encode the fragment id when
747        // requesting permissions from a fragment. Hence, requestPermissions()
748        // should validate the code against that but we cannot override it as
749        // we can not then call super and also the ActivityCompat would call
750        // back to this override. To handle this we use dependency inversion
751        // where we are the validator of request codes when requesting
752        // permissions in ActivityCompat.
753        if (mRequestedPermissionsFromFragment) {
754            mRequestedPermissionsFromFragment = false;
755        } else if ((requestCode & 0xffffff00) != 0) {
756            throw new IllegalArgumentException("Can only use lower 8 bits for requestCode");
757        }
758    }
759
760    /**
761     * Callback for the result from requesting permissions. This method
762     * is invoked for every call on {@link #requestPermissions(String[], int)}.
763     *
764     * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
765     * @param permissions The requested permissions. Never null.
766     * @param grantResults The grant results for the corresponding permissions
767     *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
768     *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
769     *
770     * @see #requestPermissions(String[], int)
771     */
772    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
773            @NonNull int[] grantResults) {
774        int index = (requestCode>>8)&0xff;
775        if (index != 0) {
776            index--;
777            final int activeFragmentsCount = mFragments.getActiveFragmentsCount();
778            if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) {
779                Log.w(TAG, "Activity result fragment index out of range: 0x"
780                        + Integer.toHexString(requestCode));
781                return;
782            }
783            final List<Fragment> activeFragments =
784                    mFragments.getActiveFragments(new ArrayList<Fragment>(activeFragmentsCount));
785            Fragment frag = activeFragments.get(index);
786            if (frag == null) {
787                Log.w(TAG, "Activity result no fragment exists for index: 0x"
788                        + Integer.toHexString(requestCode));
789            } else {
790                frag.onRequestPermissionsResult(requestCode&0xff, permissions, grantResults);
791            }
792        }
793    }
794
795    /**
796     * Called by Fragment.startActivityForResult() to implement its behavior.
797     */
798    public void startActivityFromFragment(Fragment fragment, Intent intent,
799            int requestCode) {
800        if (requestCode == -1) {
801            super.startActivityForResult(intent, -1);
802            return;
803        }
804        if ((requestCode&0xffff0000) != 0) {
805            throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
806        }
807        super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
808    }
809
810    /**
811     * Called by Fragment.requestPermissions() to implement its behavior.
812     */
813    private void requestPermissionsFromFragment(Fragment fragment, String[] permissions,
814            int requestCode) {
815        if (requestCode == -1) {
816            ActivityCompat.requestPermissions(this, permissions, requestCode);
817            return;
818        }
819        if ((requestCode&0xffffff00) != 0) {
820            throw new IllegalArgumentException("Can only use lower 8 bits for requestCode");
821        }
822        mRequestedPermissionsFromFragment = true;
823        ActivityCompat.requestPermissions(this, permissions,
824                ((fragment.mIndex + 1) << 8) + (requestCode & 0xff));
825    }
826
827    class HostCallbacks extends FragmentHostCallback<FragmentActivity> {
828        public HostCallbacks() {
829            super(FragmentActivity.this /*fragmentActivity*/);
830        }
831
832        @Override
833        public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
834            FragmentActivity.this.dump(prefix, fd, writer, args);
835        }
836
837        @Override
838        public boolean onShouldSaveFragmentState(Fragment fragment) {
839            return !isFinishing();
840        }
841
842        @Override
843        public LayoutInflater onGetLayoutInflater() {
844            return FragmentActivity.this.getLayoutInflater().cloneInContext(FragmentActivity.this);
845        }
846
847        @Override
848        public FragmentActivity onGetHost() {
849            return FragmentActivity.this;
850        }
851
852        @Override
853        public void onSupportInvalidateOptionsMenu() {
854            FragmentActivity.this.supportInvalidateOptionsMenu();
855        }
856
857        @Override
858        public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode) {
859            FragmentActivity.this.startActivityFromFragment(fragment, intent, requestCode);
860        }
861
862        @Override
863        public void onRequestPermissionsFromFragment(@NonNull Fragment fragment,
864                @NonNull String[] permissions, int requestCode) {
865            FragmentActivity.this.requestPermissionsFromFragment(fragment, permissions,
866                    requestCode);
867        }
868
869        @Override
870        public boolean onShouldShowRequestPermissionRationale(@NonNull String permission) {
871            return ActivityCompat.shouldShowRequestPermissionRationale(
872                    FragmentActivity.this, permission);
873        }
874
875        @Override
876        public boolean onHasWindowAnimations() {
877            return getWindow() != null;
878        }
879
880        @Override
881        public int onGetWindowAnimations() {
882            final Window w = getWindow();
883            return (w == null) ? 0 : w.getAttributes().windowAnimations;
884        }
885
886        @Override
887        public void onAttachFragment(Fragment fragment) {
888            FragmentActivity.this.onAttachFragment(fragment);
889        }
890
891        @Nullable
892        @Override
893        public View onFindViewById(int id) {
894            return FragmentActivity.this.findViewById(id);
895        }
896
897        @Override
898        public boolean onHasView() {
899            final Window w = getWindow();
900            return (w != null && w.peekDecorView() != null);
901        }
902    }
903}
904