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