Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2006 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package android.app;
  
  import android.net.Uri;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  
  
  import java.util.HashMap;

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(int). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with android.R.attr set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:

To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml.

The Activity class is an important part of an application's overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform's application model. For a detailed perspective on the structure of Android applications and lifecycles, please read the Dev Guide document on Application Fundamentals.

Topics covered here:

  1. Activity Lifecycle
  2. Configuration Changes
  3. Starting Activities and Getting Results
  4. Saving Persistent State
  5. Permissions
  6. Process Lifecycle

Activity Lifecycle

Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

An activity has essentially four states:

  • If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  • If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  • If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.

There are three key loops you may be interested in monitoring within your activity:

  • The entire lifetime of an activity happens between the first call to onCreate(android.os.Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
  • The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a android.content.BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user an no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
  • The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(android.os.Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.

 public class Activity extends ApplicationContext {
     protected void onCreate(Bundle savedInstanceState);

     protected void onStart();
     
     protected void onRestart();

     protected void onResume();

     protected void onPause();

     protected void onStop();

     protected void onDestroy();
 }
 

In general the movement through an activity's lifecycle looks like this:

MethodDescriptionKillable?Next
onCreate()Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.

Always followed by onStart().

NoonStart()
    onRestart()Called after your activity has been stopped, prior to it being started again.

Always followed by onStart()

NoonStart()
onStart()Called when the activity is becoming visible to the user.

Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

NoonResume() or onStop()
    onResume()Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

NoonPause()
onPause()Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.

Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

YesonResume() or
onStop()
onStop()Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.

Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

YesonRestart() or
onDestroy()
onDestroy()The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.Yesnothing

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(android.os.Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(android.os.Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(android.os.Bundle) because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

For those methods that are not marked as being killable, the activity's process will not be killed by the system starting from the time the method is called and continuing after it returns. Thus an activity is in the killable state, for example, between after onPause() to the start of onResume().

Configuration Changes

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.

Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(android.os.Bundle).

This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.

In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity's onConfigurationChanged(android.content.res.Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(android.content.res.Configuration) will not be called.

Starting Activities and Getting Results

The startActivity(android.content.Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.

Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(android.content.Intent,int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int,int,android.content.Intent) method.

When an activity exits, it can call setResult(int) to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent's Activity.onActivityResult(), along with the integer identifier it originally supplied.

If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.

 public class MyActivity extends Activity {
     ...

     static final int PICK_CONTACT_REQUEST = 0;

     protected boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             // When the user center presses, let them pick a contact.
             startActivityForResult(
                 new Intent(Intent.ACTION_PICK,
                 new Uri("content://contacts")),
                 PICK_CONTACT_REQUEST);
            return true;
         }
         return false;
     }

     protected void onActivityResult(int requestCode, int resultCode,
             Intent data) {
         if (requestCode == PICK_CONTACT_REQUEST) {
             if (resultCode == RESULT_OK) {
                 // A contact was picked.  Here we will just display it
                 // to the user.
                 startActivity(new Intent(Intent.ACTION_VIEW, data));
             }
         }
     }
 }
 

Saving Persistent State

There are generally two kinds of persistent state than an activity will deal with: shared document-like data (typically stored in a SQLite database using a content provider) and internal state such as user preferences.

For content provider data, we suggest that activities use a "edit in place" user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:

  • When creating a new document, the backing database entry or file for it is created immediately. For example, if the user chooses to write a new e-mail, a new entry for that e-mail is created as soon as they start entering data, so that if they go to any other activity after that point this e-mail will now appear in the list of drafts.

  • When an activity's onPause() method is called, it should commit to the backing content provider or file any changes the user has made. This ensures that those changes will be seen by any other activity that is about to run. You will probably want to commit your data even more aggressively at key times during your activity's lifecycle: for example before starting a new activity, before finishing your own activity, when the user switches between input fields, etc.

This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been paused. Note this implies that the user pressing BACK from your activity does not mean "cancel" -- it means to leave the activity with its current contents saved away. Cancelling edits in an activity must be provided through some other mechanism, such as an explicit "revert" or "undo" option.

See the content package for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.

The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user's preferred initial display in a calendar (day view or week view) or the user's default home page in a web browser.

Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages -- for that you will need a content provider.)

Here is an excerpt from a calendar activity that stores the user's preferred view mode in its persistent settings:

 public class CalendarActivity extends Activity {
     ...

     static final int DAY_VIEW_MODE = 0;
     static final int WEEK_VIEW_MODE = 1;

     private SharedPreferences mPrefs;
     private int mCurViewMode;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         SharedPreferences mPrefs = getSharedPreferences();
         mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
     }

     protected void onPause() {
         super.onPause();
 
         SharedPreferences.Editor ed = mPrefs.edit();
         ed.putInt("view_mode", mCurViewMode);
         ed.commit();
     }
 }
 

Permissions

The ability to start a particular Activity can be enforced when it is declared in its manifest's <activity> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start that activity.

See the Security and Permissions document for more information on permissions and security in general.

Process Lifecycle

The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user's interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).

  1. The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.

  2. A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.

  3. A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(android.os.Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(android.os.Bundle) so that it can restart itself in the same state as the user last left it.

  4. An empty process is one hosting no activities or other application components (such as Service or android.content.BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around.

Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application will it is executing. To accomplish this, your Activity should start a Service in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished.

 
 public class Activity extends ContextThemeWrapper
         implements LayoutInflater.Factory,
         Window.CallbackKeyEvent.Callback,
     private static final String TAG = "Activity";

    
Standard activity result: operation canceled.
 
     public static final int RESULT_CANCELED    = 0;
    
Standard activity result: operation succeeded.
 
     public static final int RESULT_OK           = -1;
    
Start of user-defined activity results.
 
     public static final int RESULT_FIRST_USER   = 1;
 
     private static long sInstanceCount = 0;
 
     private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
     private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
     private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
     private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
     private static final String SAVED_SEARCH_DIALOG_KEY = "android:search_dialog";
 
     private SparseArray<DialogmManagedDialogs;
 
     // set by the thread after the constructor and before onCreate(Bundle savedInstanceState) is called.
     private IBinder mToken;
     /*package*/ String mEmbeddedID;
     private Application mApplication;
     private Intent mIntent;
     private ComponentName mComponent;
     /*package*/ ActivityInfo mActivityInfo;
     /*package*/ ActivityThread mMainThread;
     /*package*/ Object mLastNonConfigurationInstance;
     Activity mParent;
     boolean mCalled;
     private boolean mResumed;
     private boolean mStopped;
     boolean mFinished;
     boolean mStartedActivity;
     /*package*/ int mConfigChangeFlags;
     /*package*/ Configuration mCurrentConfig;
 
     private Window mWindow;
 
     private WindowManager mWindowManager;
     /*package*/ View mDecor = null;
     /*package*/ boolean mWindowAdded = false;
     /*package*/ boolean mVisibleFromServer = false;
     /*package*/ boolean mVisibleFromClient = true;
 
     private CharSequence mTitle;
     private int mTitleColor = 0;
 
     private static final class ManagedCursor {
         ManagedCursor(Cursor cursor) {
              = cursor;
              = false;
              = false;
         }
 
         private final Cursor mCursor;
         private boolean mReleased;
         private boolean mUpdated;
     }
     private final ArrayList<ManagedCursormManagedCursors =
         new ArrayList<ManagedCursor>();
 
     // protected by synchronized (this) 
     int mResultCode = ;
     Intent mResultData = null;
 
     private boolean mTitleReady = false;
 
     private int mDefaultKeyMode = ;
     private SpannableStringBuilder mDefaultKeySsb = null;
     
     protected static final int[] FOCUSED_STATE_SET = {com.android.internal.R.attr.state_focused};
 
     private Thread mUiThread;
     private final Handler mHandler = new Handler();
 
     public Activity() {
         ++;
     }
 
 
     @Override
     protected void finalize() throws Throwable {
         super.finalize();
         --;
     }
     
     public static long getInstanceCount() {
         return ;
     }

    
Return the intent that started this activity.
 
     public Intent getIntent() {
         return ;
     }

    
Change the intent returned by getIntent(). This holds a reference to the given intent; it does not copy it. Often used in conjunction with onNewIntent(android.content.Intent).

Parameters:
newIntent The new Intent object to return from getIntent
See also:
getIntent()
onNewIntent(android.content.Intent)
  
     public void setIntent(Intent newIntent) {
          = newIntent;
     }

    
Return the application that owns this activity.
 
     public final Application getApplication() {
         return ;
     }

    
Is this activity embedded inside of another activity?
 
     public final boolean isChild() {
         return  != null;
     }
    
    
Return the parent activity if this view is an embedded child.
 
     public final Activity getParent() {
         return ;
     }

    
Retrieve the window manager for showing custom windows.
 
     public WindowManager getWindowManager() {
         return ;
     }

    
Retrieve the current android.view.Window for the activity. This can be used to directly access parts of the Window API that are not available through Activity/Screen.

Returns:
Window The current window, or null if the activity is not visual.
 
     public Window getWindow() {
         return ;
     }

    
Calls android.view.Window.getCurrentFocus() on the Window of this Activity to return the currently focused view.

Returns:
View The current View with focus or null.
See also:
getWindow()
android.view.Window.getCurrentFocus()
 
     public View getCurrentFocus() {
         return  != null ? .getCurrentFocus() : null;
     }
 
     @Override
     public int getWallpaperDesiredMinimumWidth() {
         int width = super.getWallpaperDesiredMinimumWidth();
         return width <= 0 ? getWindowManager().getDefaultDisplay().getWidth() : width;
     }
 
     @Override
     public int getWallpaperDesiredMinimumHeight() {
         int height = super.getWallpaperDesiredMinimumHeight();
         return height <= 0 ? getWindowManager().getDefaultDisplay().getHeight() : height;
     }

    
Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String) to retrieve cursors for data being displayed, etc.

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters:
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(android.os.Bundle). Note: Otherwise it is null.
See also:
onStart()
onSaveInstanceState(android.os.Bundle)
onRestoreInstanceState(android.os.Bundle)
onPostCreate(android.os.Bundle)
 
     protected void onCreate(Bundle savedInstanceState) {
                 com.android.internal.R.styleable.Window_windowNoDisplay, true);
          = true;
     }

    
The hook for ActivityThread to restore the state of this activity. Calls onSaveInstanceState(android.os.Bundle) and restoreManagedDialogs(android.os.Bundle).

Parameters:
savedInstanceState contains the saved state
 
     final void performRestoreInstanceState(Bundle savedInstanceState) {
         onRestoreInstanceState(savedInstanceState);
         restoreManagedDialogs(savedInstanceState);
         
         // Also restore the state of a search dialog (if any)
         // TODO more generic than just this manager
         SearchManager searchManager = 
         searchManager.restoreSearchDialog(savedInstanceState);
     }

    
This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in state. Most implementations will simply use onCreate(android.os.Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(android.os.Bundle).

This method is called between onStart() and onPostCreate(android.os.Bundle).

 
     protected void onRestoreInstanceState(Bundle savedInstanceState) {
         if ( != null) {
             Bundle windowState = savedInstanceState.getBundle();
             if (windowState != null) {
                 .restoreHierarchyState(windowState);
             }
         }
     }
    
    
Restore the state of any saved managed dialogs.

Parameters:
savedInstanceState The bundle to restore from.
 
     private void restoreManagedDialogs(Bundle savedInstanceState) {
         final Bundle b = savedInstanceState.getBundle();
         if (b == null) {
             return;
         }
 
         final int[] ids = b.getIntArray();
         final int numDialogs = ids.length;
          = new SparseArray<Dialog>(numDialogs);
         for (int i = 0; i < numDialogsi++) {
             final Integer dialogId = ids[i];
             Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId));
             if (dialogState != null) {
                 final Dialog dialog = onCreateDialog(dialogId);
                 dialog.onRestoreInstanceState(dialogState);
                 .put(dialogIddialog);
             }
         }
     }
 
     private String savedDialogKeyFor(int key) {
         return  + key;
     }


    
Called when activity start-up is complete (after onStart() and onRestoreInstanceState(android.os.Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters:
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(android.os.Bundle). Note: Otherwise it is null.
See also:
onCreate(android.os.Bundle)
 
     protected void onPostCreate(Bundle savedInstanceState) {
         if (!isChild()) {
              = true;
             onTitleChanged(getTitle(), getTitleColor());
         }
          = true;
     }

    
Called after onCreate(android.os.Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

 
     protected void onStart() {
          = true;
     }

    
Called after onStop() when the current activity is being re-displayed to the user (the user has navigated back to it). It will be followed by onStart() and then onResume().

For activities that are using raw android.database.Cursor objects (instead of creating them through managedQuery(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String), this is usually the place where the cursor should be requeried (because you had deactivated it in onStop().

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

 
     protected void onRestart() {
          = true;
     }

    
Called after onRestoreInstanceState(android.os.Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.

Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

 
     protected void onResume() {
          = true;
     }

    
Called when activity resume is complete (after onResume() has been called). Applications will generally not implement this method; it is intended for system classes to do final setup after application resume code has run.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

See also:
onResume()
 
     protected void onPostResume() {
         final Window win = getWindow();
         if (win != nullwin.makeActive();
          = true;
     }

    
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(android.content.Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(android.content.Intent) to update it to this new Intent.

Parameters:
intent The new intent that was started for the activity.
See also:
getIntent()
setIntent(android.content.Intent)
onResume()
 
     protected void onNewIntent(Intent intent) {
     }

    
The hook for ActivityThread to save the state of this activity. Calls onSaveInstanceState(android.os.Bundle) and saveManagedDialogs(android.os.Bundle).

Parameters:
outState The bundle to save the state to.
    final void performSaveInstanceState(Bundle outState) {
        onSaveInstanceState(outState);
        saveManagedDialogs(outState);
        // Also save the state of a search dialog (if any)
        // TODO more generic than just this manager
        SearchManager searchManager = 
        searchManager.saveSearchDialog(outState);
    }

    
Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(android.os.Bundle) or onRestoreInstanceState(android.os.Bundle) (the android.os.Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(android.os.Bundle) or onRestoreInstanceState(android.os.Bundle).

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(android.os.Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(android.os.Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(android.os.Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care of most of the UI per-instance state for you by calling android.view.View.onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(android.os.Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

Parameters:
outState Bundle in which to place your saved state.
See also:
onCreate(android.os.Bundle)
onRestoreInstanceState(android.os.Bundle)
onPause()
    protected void onSaveInstanceState(Bundle outState) {
    }

    
Save the state of any managed dialogs.

Parameters:
outState place to store the saved state.
    private void saveManagedDialogs(Bundle outState) {
        if ( == null) {
            return;
        }
        final int numDialogs = .size();
        if (numDialogs == 0) {
            return;
        }
        Bundle dialogState = new Bundle();
        int[] ids = new int[.size()];
        // save each dialog's bundle, gather the ids
        for (int i = 0; i < numDialogsi++) {
            final int key = .keyAt(i);
            ids[i] = key;
            final Dialog dialog = .valueAt(i);
            dialogState.putBundle(savedDialogKeyFor(key), dialog.onSaveInstanceState());
        }
        dialogState.putIntArray(ids);
        outState.putBundle(dialogState);
    }


    
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable mount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

In situations where the system needs more memory it may kill paused processes to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function. In general onSaveInstanceState(android.os.Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.)

After receiving this call you will usually receive a following call to onStop() (after the next activity has been resumed and displayed), however in some cases there will be a direct call back to onResume() without going through the stopped state.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

    protected void onPause() {
         = true;
    }

    
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback.

This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

    protected void onUserLeaveHint() {
    }
    
    
Generate a new thumbnail for this activity. This method is called before pausing the activity, and should draw into outBitmap the imagery for the desired thumbnail in the dimensions of that bitmap. It can use the given canvas, which is configured to draw into the bitmap, for rendering if desired.

The default implementation renders the Screen's current view hierarchy into the canvas to generate a thumbnail.

If you return false, the bitmap will be filled with a default thumbnail.

Parameters:
outBitmap The bitmap to contain the thumbnail.
canvas Can be used to render into the bitmap.
Returns:
Return true if you have drawn into the bitmap; otherwise after you return it will be filled with a default thumbnail.
See also:
onCreateDescription()
onSaveInstanceState(android.os.Bundle)
onPause()
    public boolean onCreateThumbnail(Bitmap outBitmapCanvas canvas) {
        final View view = ;
        if (view == null) {
            return false;
        }
        final int vw = view.getWidth();
        final int vh = view.getHeight();
        final int dw = outBitmap.getWidth();
        final int dh = outBitmap.getHeight();
        canvas.save();
        canvas.scale(((float)dw)/vw, ((float)dh)/vh);
        view.draw(canvas);
        canvas.restore();
        return true;
    }

    
Generate a new description for this activity. This method is called before pausing the activity and can, if desired, return some textual description of its current state to be displayed to the user.

The default implementation returns null, which will cause you to inherit the description from the previous activity. If all activities return null, generally the label of the top activity will be used as the description.

Returns:
A description of what the user is doing. It should be short and sweet (only a few words).
See also:
onCreateThumbnail(android.graphics.Bitmap,android.graphics.Canvas)
onSaveInstanceState(android.os.Bundle)
onPause()
        return null;
    }

    
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

    protected void onStop() {
         = true;
    }

    
Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(android.os.Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

    protected void onDestroy() {
         = true;
        // dismiss any dialogs we are managing.
        if ( != null) {
            final int numDialogs = .size();
            for (int i = 0; i < numDialogsi++) {
                final Dialog dialog = .valueAt(i);
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        }
        
        // also dismiss search dialog if showing
        // TODO more generic than just this manager
        SearchManager searchManager = 
        searchManager.stopSearch();
        // close any cursors we are managing.
        int numCursors = .size();
        for (int i = 0; i < numCursorsi++) {
            ManagedCursor c = .get(i);
            if (c != null) {
                c.mCursor.close();
            }
        }
    }

    
Called by the system when the device configuration changes while your activity is running. Note that this will only be called if you have selected configurations you would like to handle with the android.R.attr attribute in your manifest. If any configuration change occurs that is not selected to be reported by that attribute, then instead of reporting it the system will stop and restart the activity (to have it launched with the new configuration).

At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

Parameters:
newConfig The new device configuration.
    public void onConfigurationChanged(Configuration newConfig) {
         = true;
        
        // also update search dialog if showing
        // TODO more generic than just this manager
        SearchManager searchManager = 
        searchManager.onConfigurationChanged(newConfig);
        
        if ( != null) {
            // Pass the configuration changed event to the window
            .onConfigurationChanged(newConfig);
        }
    }
    
    
If this activity is being destroyed because it can not handle a configuration parameter being changed (and thus its onConfigurationChanged(android.content.res.Configuration) method is not being called), then you can use this method to discover the set of changes that have occurred while in the process of being destroyed. Note that there is no guarantee that these will be accurate (other changes could have happened at any time), so you should only use this as an optimization hint.

Returns:
Returns a bit field of the configuration parameters that are changing, as defined by the android.content.res.Configuration class.
    public int getChangingConfigurations() {
        return ;
    }
    
    
Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial onCreate(android.os.Bundle) and onStart() calls to the new instance, allowing you to extract any useful dynamic state from the previous instance.

Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its previous state (through the normal onSaveInstanceState(android.os.Bundle) mechanism) even if this function returns null.

Returns:
Returns the object previously returned by onRetainNonConfigurationInstance().
        return ;
    }
    
    
Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration. You can return any object you like here, including the activity instance itself, which can later be retrieved by calling getLastNonConfigurationInstance() in the new activity instance.

This function is called purely as an optimization, and you must not rely on it being called. When it is called, a number of guarantees will be made to help optimize configuration switching:

  • The function will be called between onStop() and onDestroy().
  • A new instance of the activity will always be immediately created after this one's onDestroy() is called.
  • The object you return here will always be available from the getLastNonConfigurationInstance() method of the following activity instance as described there.

These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.

Returns:
Return any Object holding the desired state to propagate to the next activity instance.
        return null;
    }
    
    
Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationChildInstances(). This will be available from the initial onCreate(android.os.Bundle) and onStart() calls to the new instance, allowing you to extract any useful dynamic state from the previous instance.

Note that the data you retrieve here should only be used as an optimization for handling configuration changes. You should always be able to handle getting a null pointer back, and an activity must still be able to restore itself to its previous state (through the normal onSaveInstanceState(android.os.Bundle) mechanism) even if this function returns null.

Returns:
Returns the object previously returned by onRetainNonConfigurationChildInstances()
    }
    
    
This method is similar to onRetainNonConfigurationInstance() except that it should return either a mapping from child activity id strings to arbitrary objects, or null. This method is intended to be used by Activity framework subclasses that control a set of child activities, such as ActivityGroup. The same guarantees and restrictions apply as for onRetainNonConfigurationInstance(). The default implementation returns null.
        return null;
    }
    
    public void onLowMemory() {
         = true;
    }
    
    
Wrapper around android.content.ContentResolver.query(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String) that gives the resulting android.database.Cursor to call startManagingCursor(android.database.Cursor) so that the activity will manage its lifecycle for you.

Parameters:
uri The URI of the content provider to query.
projection List of columns to return.
selection SQL WHERE clause.
sortOrder SQL ORDER BY clause.
Returns:
The Cursor that was returned by query().
See also:
android.content.ContentResolver.query(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String)
startManagingCursor(android.database.Cursor)
Hide:
    public final Cursor managedQuery(Uri uri,
                                     String[] projection,
                                     String selection,
                                     String sortOrder)
    {
        Cursor c = getContentResolver().query(uriprojectionselectionnullsortOrder);
        if (c != null) {
            startManagingCursor(c);
        }
        return c;
    }

    
Wrapper around android.content.ContentResolver.query(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String) that gives the resulting android.database.Cursor to call startManagingCursor(android.database.Cursor) so that the activity will manage its lifecycle for you.

Parameters:
uri The URI of the content provider to query.
projection List of columns to return.
selection SQL WHERE clause.
selectionArgs The arguments to selection, if any ?s are pesent
sortOrder SQL ORDER BY clause.
Returns:
The Cursor that was returned by query().
See also:
android.content.ContentResolver.query(android.net.Uri,java.lang.String[],java.lang.String,java.lang.String[],java.lang.String)
startManagingCursor(android.database.Cursor)
    public final Cursor managedQuery(Uri uri,
                                     String[] projection,
                                     String selection,
                                     String[] selectionArgs,
                                     String sortOrder)
    {
        Cursor c = getContentResolver().query(uriprojectionselectionselectionArgssortOrder);
        if (c != null) {
            startManagingCursor(c);
        }
        return c;
    }

    
Wrapper around android.database.Cursor.commitUpdates() that takes care of noting that the Cursor needs to be requeried. You can call this method in onPause() or onStop() to have the system call android.database.Cursor.requery() for you if the activity is later resumed. This allows you to avoid determing when to do the requery yourself (which is required for the Cursor to see any data changes that were committed with it).

    public void managedCommitUpdates(Cursor c) {
        synchronized () {
            final int N = .size();
            for (int i=0; i<Ni++) {
                ManagedCursor mc = .get(i);
                if (mc.mCursor == c) {
                    c.commitUpdates();
                    mc.mUpdated = true;
                    return;
                }
            }
            throw new RuntimeException(
                "Cursor " + c + " is not currently managed");
        }
    }

    
This method allows the activity to take care of managing the given android.database.Cursor's lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call android.database.Cursor.deactivate() on the given Cursor, and when it is later restarted it will call android.database.Cursor.requery() for you. When the activity is destroyed, all managed Cursors will be closed automatically.

    public void startManagingCursor(Cursor c) {
        synchronized () {
            .add(new ManagedCursor(c));
        }
    }

    
Given a Cursor that was previously given to startManagingCursor(android.database.Cursor), stop the activity's management of that cursor.

Parameters:
c The Cursor that was being managed.
See also:
startManagingCursor(android.database.Cursor)
    public void stopManagingCursor(Cursor c) {
        synchronized () {
            final int N = .size();
            for (int i=0; i<Ni++) {
                ManagedCursor mc = .get(i);
                if (mc.mCursor == c) {
                    .remove(i);
                    break;
                }
            }
        }
    }

    
Control whether this activity is required to be persistent. By default activities are not persistent; setting this to true will prevent the system from stopping this activity or its process when running low on resources.

You should avoid using this method, it has severe negative consequences on how well the system can manage its resources. A better approach is to implement an application service that you control with android.content.Context.startService(android.content.Intent) and android.content.Context.stopService(android.content.Intent).

Parameters:
isPersistent Control whether the current activity must be persistent, true if so, false for the normal behavior.
    public void setPersistent(boolean isPersistent) {
        if ( == null) {
            try {
                ActivityManagerNative.getDefault()
                    .setPersistent(isPersistent);
            } catch (RemoteException e) {
                // Empty
            }
        } else {
            throw new RuntimeException("setPersistent() not yet supported for embedded activities");
        }
    }

    
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(android.os.Bundle).

Returns:
The view if found or null otherwise.
    public View findViewById(int id) {
        return getWindow().findViewById(id);
    }

    
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Parameters:
layoutResID Resource ID to be inflated.
    public void setContentView(int layoutResID) {
        getWindow().setContentView(layoutResID);
    }

    
Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarhcy.

Parameters:
view The desired content to display.
    public void setContentView(View view) {
        getWindow().setContentView(view);
    }

    
Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. It can itself be a complex view hierarhcy.

Parameters:
view The desired content to display.
params Layout parameters for the view.
    public void setContentView(View viewViewGroup.LayoutParams params) {
        getWindow().setContentView(viewparams);
    }

    
Add an additional content view to the activity. Added after any existing ones in the activity -- existing views are NOT removed.

Parameters:
view The desired content to display.
params Layout parameters for the view.
    public void addContentView(View viewViewGroup.LayoutParams params) {
        getWindow().addContentView(viewparams);
    }

    
Use with setDefaultKeyMode(int) to turn off default handling of keys.

    static public final int DEFAULT_KEYS_DISABLE = 0;
    
Use with setDefaultKeyMode(int) to launch the dialer during default key handling.

    static public final int DEFAULT_KEYS_DIALER = 1;
    
Use with setDefaultKeyMode(int) to execute a menu shortcut in default key handling.

That is, the user does not need to hold down the menu key to execute menu shortcuts.

    static public final int DEFAULT_KEYS_SHORTCUT = 2;
    
Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start an application-defined search. (If the application or activity does not actually define a search, the the keys will be ignored.)

See android.app.SearchManager for more details.

    static public final int DEFAULT_KEYS_SEARCH_LOCAL = 3;

    
Use with setDefaultKeyMode(int) to specify that unhandled keystrokes will start a global search (typically web search, but some platforms may define alternate methods for global search)

See android.app.SearchManager for more details.

    static public final int DEFAULT_KEYS_SEARCH_GLOBAL = 4;

    
Select the default key handling for this activity. This controls what will happen to key events that are not otherwise handled. The default mode (DEFAULT_KEYS_DISABLE) will simply drop them on the floor. Other modes allow you to launch the dialer (DEFAULT_KEYS_DIALER), execute a shortcut in your options menu without requiring the menu key be held down (DEFAULT_KEYS_SHORTCUT), or launch a search (DEFAULT_KEYS_SEARCH_LOCAL and DEFAULT_KEYS_SEARCH_GLOBAL).

Note that the mode selected here does not impact the default handling of system keys, such as the "back" and "menu" keys, and your activity and its views always get a first chance to receive and handle all application keys.

    public final void setDefaultKeyMode(int mode) {
         = mode;
        
        // Some modes use a SpannableStringBuilder to track & dispatch input events
        // This list must remain in sync with the switch in onKeyDown()
        switch (mode) {
        case :
        case :
             = null;      // not used in these modes
            break;
        case :
        case :
        case :
             = new SpannableStringBuilder();
            Selection.setSelection(,0);
            break;
        default:
            throw new IllegalArgumentException();
        }
    }

    
Called when a key was pressed down and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

If the focused view didn't want this event, this method is called.

The default implementation handles KEYCODE_BACK to stop the activity and go back, and other default key handling if configured with setDefaultKeyMode(int).

Returns:
Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated.
See also:
onKeyUp(int,android.view.KeyEvent)
android.view.KeyEvent
    public boolean onKeyDown(int keyCodeKeyEvent event)  {
        if (keyCode == . && event.getRepeatCount() == 0) {
            finish();
            return true;
        }
        
        if ( == ) {
            return false;
        } else if ( == ) {
            return getWindow().performPanelShortcut(.
                                                    keyCodeevent.);
        } else {
            // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_*
            boolean clearSpannable = false;
            boolean handled;
            if ((event.getRepeatCount() != 0) || event.isSystem()) {
                clearSpannable = true;
                handled = false;
            } else {
                handled = TextKeyListener.getInstance().onKeyDown(null
                                                                  keyCodeevent);
                if (handled && .length() > 0) {
                    // something useable has been typed - dispatch it now.
                    final String str = .toString();
                    clearSpannable = true;
                    
                    switch () {
                    case :
                        Intent intent = new Intent(.,  Uri.parse("tel:" + str));
                        intent.addFlags(.);
                        startActivity(intent);    
                        break;
                    case :
                        startSearch(strfalsenullfalse);
                        break;
                    case :
                        startSearch(strfalsenulltrue);
                        break;
                    }
                }
            }
            if (clearSpannable) {
                .clear();
                .clearSpans();
                Selection.setSelection(,0);
            }
            return handled;
        }
    }

    
Called when a key was released and not handled by any of the views inside of the activity. So, for example, key presses while the cursor is inside a TextView will not trigger the event (unless it is a navigation to another object) because TextView handles its own key presses.

Returns:
Return true to prevent this event from being propagated further, or false to indicate that you have not handled this event and it should continue to be propagated.
See also:
onKeyDown(int,android.view.KeyEvent)
android.view.KeyEvent
    public boolean onKeyUp(int keyCodeKeyEvent event) {
        return false;
    }

    
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
    public boolean onKeyMultiple(int keyCodeint repeatCountKeyEvent event) {
        return false;
    }
    
    
Called when a touch screen event was not handled by any of the views under it. This is most useful to process touch events that happen outside of your window bounds, where there is no view to receive it.

Parameters:
event The touch screen event being processed.
Returns:
Return true if you have consumed the event, false if you haven't. The default implementation always returns false.
    public boolean onTouchEvent(MotionEvent event) {
        return false;
    }
    
    
Called when the trackball was moved and not handled by any of the views inside of the activity. So, for example, if the trackball moves while focus is on a button, you will receive a call here because buttons do not normally do anything with trackball events. The call here happens before trackball movements are converted to DPAD key events, which then get sent back to the view hierarchy, and will be processed at the point for things like focus navigation.

Parameters:
event The trackball event being processed.
Returns:
Return true if you have consumed the event, false if you haven't. The default implementation always returns false.
    public boolean onTrackballEvent(MotionEvent event) {
        return false;
    }
    
    
Called whenever a key, touch, or trackball event is dispatched to the activity. Implement this method if you wish to know that the user has interacted with the device in some way while your activity is running. This callback and onUserLeaveHint() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

All calls to your activity's onUserLeaveHint() callback will be accompanied by calls to onUserInteraction(). This ensures that your activity will be told of relevant user activity such as pulling down the notification pane and touching an item there.

Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow.

    public void onUserInteraction() {
    }
    
    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
        // Update window manager if: we have a view, that view is
        // attached to its parent (which will be a RootView), and
        // this activity is not embedded.
        if ( == null) {
            View decor = ;
            if (decor != null && decor.getParent() != null) {
                getWindowManager().updateViewLayout(decorparams);
            }
        }
    }
    public void onContentChanged() {
    }

    
Called when the current android.view.Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user.

Note that this provides information what global focus state, which is managed independently of activity lifecycles. As such, while focus changes will generally have some relation to lifecycle changes (an activity that is stopped will not generally get window focus), you should not rely on any particular order between the callbacks here and those in the other lifecycle methods such as onResume().

As a general rule, however, a resumed activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.

Parameters:
hasFocus Whether the window of this activity has focus.
See also:
hasWindowFocus()
onResume()
    public void onWindowFocusChanged(boolean hasFocus) {
    }
    
    
Returns true if this activity's main window currently has window focus. Note that this is not the same as the view itself having focus.

Returns:
True if this activity's main window currently has window focus.
See also:
onWindowAttributesChanged(android.view.WindowManager.LayoutParams)
    public boolean hasWindowFocus() {
        Window w = getWindow();
        if (w != null) {
            View d = w.getDecorView();
            if (d != null) {
                return d.hasWindowFocus();
            }
        }
        return false;
    }
    
    
Called to process key events. You can override this to intercept all key events before they are dispatched to the window. Be sure to call this implementation for key events that should be handled normally.

Parameters:
event The key event.
Returns:
boolean Return true if this event was consumed.
    public boolean dispatchKeyEvent(KeyEvent event) {
        onUserInteraction();
        if (getWindow().superDispatchKeyEvent(event)) {
            return true;
        }
        return event.dispatch(this);
    }

    
Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Parameters:
ev The touch screen event.
Returns:
boolean Return true if this event was consumed.
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == .) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    
    
Called to process trackball events. You can override this to intercept all trackball events before they are dispatched to the window. Be sure to call this implementation for trackball events that should be handled normally.

Parameters:
ev The trackball event.
Returns:
boolean Return true if this event was consumed.
    public boolean dispatchTrackballEvent(MotionEvent ev) {
        onUserInteraction();
        if (getWindow().superDispatchTrackballEvent(ev)) {
            return true;
        }
        return onTrackballEvent(ev);
    }
    
    
Default implementation of android.view.Window.Callback.onCreatePanelView(int) for activities. This simply returns null so that all panel sub-windows will have the default menu behavior.
    public View onCreatePanelView(int featureId) {
        return null;
    }

    
Default implementation of android.view.Window.Callback.onCreatePanelMenu(int,android.view.Menu) for activities. This calls through to the new onCreateOptionsMenu(android.view.Menu) method for the android.view.Window.FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.
    public boolean onCreatePanelMenu(int featureIdMenu menu) {
        if (featureId == .) {
            return onCreateOptionsMenu(menu);
        }
        return false;
    }

    
Default implementation of android.view.Window.Callback.onPreparePanel(int,android.view.View,android.view.Menu) for activities. This calls through to the new onPrepareOptionsMenu(android.view.Menu) method for the android.view.Window.FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.
    public boolean onPreparePanel(int featureIdView viewMenu menu) {
        if (featureId == . && menu != null) {
            boolean goforit = onPrepareOptionsMenu(menu);
            return goforit && menu.hasVisibleItems();
        }
        return true;
    }

    

Returns:
The default implementation returns true.
    public boolean onMenuOpened(int featureIdMenu menu) {
        return true;
    }

    
Default implementation of android.view.Window.Callback.onMenuItemSelected(int,android.view.MenuItem) for activities. This calls through to the new onOptionsItemSelected(android.view.MenuItem) method for the android.view.Window.FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes.
    public boolean onMenuItemSelected(int featureIdMenuItem item) {
        switch (featureId) {
            case .:
                // Put event logging here so it gets called even if subclass
                // doesn't call through to superclass's implmeentation of each
                // of these methods below
                EventLog.writeEvent(50000, 0, item.getTitleCondensed());
                return onOptionsItemSelected(item);
                
            case .:
                EventLog.writeEvent(50000, 1, item.getTitleCondensed());
                return onContextItemSelected(item);
                
            default:
                return false;
        }
    }
    
    
Default implementation of android.view.Window.Callback.onPanelClosed(int,android.view.Menu) for activities. This calls through to onOptionsMenuClosed(android.view.Menu) method for the android.view.Window.FEATURE_OPTIONS_PANEL panel, so that subclasses of Activity don't need to deal with feature codes. For context menus (android.view.Window.FEATURE_CONTEXT_MENU), the onContextMenuClosed(android.view.Menu) will be called.
    public void onPanelClosed(int featureIdMenu menu) {
        switch (featureId) {
            case .:
                onOptionsMenuClosed(menu);
                break;
                
            case .:
                onContextMenuClosed(menu);
                break;
        }
    }

    
Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu.

This is only called once, the first time the options menu is displayed. To update the menu every time it is displayed, see onPrepareOptionsMenu(android.view.Menu).

The default implementation populates the menu with standard system menu items. These are placed in the android.view.Menu.CATEGORY_SYSTEM group so that they will be correctly ordered with application-defined menu items. Deriving classes should always call through to the base implementation.

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

When you add items to the menu, you can implement the Activity's onOptionsItemSelected(android.view.MenuItem) method to handle them there.

Parameters:
menu The options menu in which you place your items.
Returns:
You must return true for the menu to be displayed; if you return false it will not be shown.
See also:
onPrepareOptionsMenu(android.view.Menu)
onOptionsItemSelected(android.view.MenuItem)
    public boolean onCreateOptionsMenu(Menu menu) {
        if ( != null) {
            return .onCreateOptionsMenu(menu);
        }
        return true;
    }

    
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.

Parameters:
menu The options menu as last shown or first initialized by onCreateOptionsMenu().
Returns:
You must return true for the menu to be displayed; if you return false it will not be shown.
See also:
onCreateOptionsMenu(android.view.Menu)
    public boolean onPrepareOptionsMenu(Menu menu) {
        if ( != null) {
            return .onPrepareOptionsMenu(menu);
        }
        return true;
    }

    
This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters:
item The menu item that was selected.
Returns:
boolean Return false to allow normal menu processing to proceed, true to consume it here.
See also:
onCreateOptionsMenu(android.view.Menu)
    public boolean onOptionsItemSelected(MenuItem item) {
        if ( != null) {
            return .onOptionsItemSelected(item);
        }
        return false;
    }

    
This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Parameters:
menu The options menu as last shown or first initialized by onCreateOptionsMenu().
    public void onOptionsMenuClosed(Menu menu) {
        if ( != null) {
            .onOptionsMenuClosed(menu);
        }
    }
    
    
Programmatically opens the options menu. If the options menu is already open, this method does nothing.
    public void openOptionsMenu() {
    }
    
    
Progammatically closes the options menu. If the options menu is already closed, this method does nothing.
    public void closeOptionsMenu() {
    }

    
Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu(android.view.Menu), this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for android.widget.AdapterView subclasses, this can be found in the menuInfo)).

Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected.

It is not safe to hold onto the context menu after this method returns.

    public void onCreateContextMenu(ContextMenu menuView vContextMenuInfo menuInfo) {
    }

    
Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the android.view.View.OnCreateContextMenuListener on the view to this activity, so onCreateContextMenu(android.view.ContextMenu,android.view.View,android.view.ContextMenu.ContextMenuInfo) will be called when it is time to show the context menu.

Parameters:
view The view that should show a context menu.
See also:
unregisterForContextMenu(android.view.View)
    public void registerForContextMenu(View view) {
        view.setOnCreateContextMenuListener(this);
    }
    
    
Prevents a context menu to be shown for the given view. This method will remove the android.view.View.OnCreateContextMenuListener on the view.

Parameters:
view The view that should stop showing a context menu.
See also:
registerForContextMenu(android.view.View)
    public void unregisterForContextMenu(View view) {
        view.setOnCreateContextMenuListener(null);
    }
    
    
Programmatically opens the context menu for a particular view. The view should have been added via registerForContextMenu(android.view.View).

Parameters:
view The view to show the context menu for.
    public void openContextMenu(View view) {
        view.showContextMenu();
    }
    
    
Programmatically closes the most recently opened context menu, if showing.
    public void closeContextMenu() {
    }
    
    
This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

Use android.view.MenuItem.getMenuInfo() to get extra information set by the View that added this menu item.

Derived classes should call through to the base class for it to perform the default menu handling.

Parameters:
item The context menu item that was selected.
Returns:
boolean Return false to allow normal context menu processing to proceed, true to consume it here.
    public boolean onContextItemSelected(MenuItem item) {
        if ( != null) {
            return .onContextItemSelected(item);
        }
        return false;
    }

    
This hook is called whenever the context menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).

Parameters:
menu The context menu that is being closed.
    public void onContextMenuClosed(Menu menu) {
        if ( != null) {
            .onContextMenuClosed(menu);
        }
    }

    
Callback for creating dialogs that are managed (saved and restored) for you by the activity. If you use showDialog(int), the activity will call through to this method the first time, and hang onto it thereafter. Any dialog that is created by this method will automatically be saved and restored for you, including whether it is showing. If you would like the activity to manage the saving and restoring dialogs for you, you should override this method and handle any ids that are passed to showDialog(int). If you would like an opportunity to prepare your dialog before it is shown, override onPrepareDialog(int,android.app.Dialog).

Parameters:
id The id of the dialog.
Returns:
The dialog
See also:
onPrepareDialog(int,android.app.Dialog)
showDialog(int)
dismissDialog(int)
removeDialog(int)
    protected Dialog onCreateDialog(int id) {
        return null;
    }

    
Provides an opportunity to prepare a managed dialog before it is being shown.

Override this if you need to update a managed dialog based on the state of the application each time it is shown. For example, a time picker dialog might want to be updated with the current time. You should call through to the superclass's implementation. The default implementation will set this Activity as the owner activity on the Dialog.

Parameters:
id The id of the managed dialog.
dialog The dialog.
See also:
onCreateDialog(int)
showDialog(int)
dismissDialog(int)
removeDialog(int)
    protected void onPrepareDialog(int idDialog dialog) {
        dialog.setOwnerActivity(this);
    }

    
Show a dialog managed by this activity. A call to onCreateDialog(int) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored. Each time a dialog is shown, onPrepareDialog(int,android.app.Dialog) will be made to provide an opportunity to do any timely preparation.

    public final void showDialog(int id) {
        if ( == null) {
             = new SparseArray<Dialog>();
        }
        Dialog dialog = .get(id);
        if (dialog == null) {
            dialog = onCreateDialog(id);
            if (dialog == null) {
                throw new IllegalArgumentException("Activity#onCreateDialog did "
                        + "not create a dialog for id " + id);
            }
            dialog.dispatchOnCreate(null);
            .put(iddialog);
        }
        
        onPrepareDialog(iddialog);
        dialog.show();
    }

    
Dismiss a dialog that was previously shown via showDialog(int).

Parameters:
id The id of the managed dialog.
Throws:
java.lang.IllegalArgumentException if the id was not previously shown via showDialog(int).
See also:
onCreateDialog(int)
onPrepareDialog(int,android.app.Dialog)
showDialog(int)
removeDialog(int)
    public final void dismissDialog(int id) {
        if ( == null) {
            throw missingDialog(id);
        }
        final Dialog dialog = .get(id);
        if (dialog == null) {
            throw missingDialog(id);
        }
        dialog.dismiss();
    }

    
Creates an exception to throw if a user passed in a dialog id that is unexpected.
    private IllegalArgumentException missingDialog(int id) {
        return new IllegalArgumentException("no dialog with id " + id + " was ever "
                + "shown via Activity#showDialog");
    }

    
Removes any internal references to a dialog managed by this Activity. If the dialog is showing, it will dismiss it as part of the clean up. This can be useful if you know that you will never show a dialog again and want to avoid the overhead of saving and restoring it in the future.

    public final void removeDialog(int id) {
        if ( == null) {
            return;
        }
        final Dialog dialog = .get(id);
        if (dialog == null) {
            return;
        }
        dialog.dismiss();
        .remove(id);
    }

    
This hook is called when the user signals the desire to start a search.

You can use this function as a simple way to launch the search UI, in response to a menu item, search button, or other widgets within your activity. Unless overidden, calling this function is the same as calling:

The default implementation simply calls startSearch(null, false, null, false), launching a local search.

You can override this function to force global search, e.g. in response to a dedicated search key, or to block search entirely (by simply returning false).

Returns:
Returns true if search launched, false if activity blocks it
See also:
SearchManager
    public boolean onSearchRequested() {
        startSearch(nullfalsenullfalse); 
        return true;
    }
    
    
This hook is called to launch the search UI.

It is typically called from onSearchRequested(), either directly from Activity.onSearchRequested() or from an overridden version in any given Activity. If your goal is simply to activate search, it is preferred to call onSearchRequested(), which may have been overriden elsewhere in your Activity. If your goal is to inject specific data such as context data, it is preferred to override onSearchRequested(), so that any callers to it will benefit from the override.

Parameters:
initialQuery Any non-null non-empty string will be inserted as pre-entered text in the search query box.
selectInitialQuery If true, the intial query will be preselected, which means that any further typing will replace it. This is useful for cases where an entire pre-formed query is being inserted. If false, the selection point will be placed at the end of the inserted query. This is useful when the inserted query is text that the user entered, and the user would expect to be able to keep typing. This parameter is only meaningful if initialQuery is a non-empty string.
appSearchData An application can insert application-specific context here, in order to improve quality or specificity of its own searches. This data will be returned with SEARCH intent(s). Null if no extra data is required.
globalSearch If false, this will only launch the search that has been specifically defined by the application (which is usually defined as a local search). If no default search is defined in the current application or activity, no search will be launched. If true, this will always launch a platform-global (e.g. web-based) search instead.
See also:
SearchManager
onSearchRequested()
    public void startSearch(String initialQueryboolean selectInitialQuery
            Bundle appSearchDataboolean globalSearch) {
        // activate the search manager and start it up!
        SearchManager searchManager = (SearchManager)
                        getSystemService(.);
        searchManager.startSearch(initialQueryselectInitialQuerygetComponentName(),
                        appSearchDataglobalSearch);