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 java.util.Map;

Helper class for managing multiple running embedded activities in the same process. This class is not normally used directly, but rather created for you as part of the ActivityGroup implementation.

See also:
ActivityGroup
 
 public class LocalActivityManager {
     private static final String TAG = "LocalActivityManager";
     private static final boolean localLOGV = false || .;
 
     // Internal token for an Activity being managed by LocalActivityManager.
     private static class LocalActivityRecord extends Binder {
         LocalActivityRecord(String _idIntent _intent) {
              = _id;
              = _intent;
         }
 
         final String id;                // Unique name of this record.
         Intent intent;                  // Which activity to run here.
         ActivityInfo activityInfo;      // Package manager info about activity.
         Activity activity;              // Currently instantiated activity.
         Window window;                  // Activity's top-level window.
         Bundle instanceState;           // Last retrieved freeze state.
         int curState = ;        // Current state the activity is in.
     }
 
     static final int RESTORED = 0;      // State restored, but no startActivity().
     static final int INITIALIZING = 1;  // Ready to launch (after startActivity()).
     static final int CREATED = 2;       // Created, not started or resumed.
     static final int STARTED = 3;       // Created and started, not resumed.
     static final int RESUMED = 4;       // Created started and resumed.
     static final int DESTROYED = 5;     // No longer with us.
     
    
Thread our activities are running in.
 
     private final ActivityThread mActivityThread;
    
The containing activity that owns the activities we create.
 
     private final Activity mParent;

    
The activity that is currently resumed.
 
     private LocalActivityRecord mResumed;
    
id -> record of all known activities.
 
     private final Map<StringLocalActivityRecordmActivities
             = new HashMap<StringLocalActivityRecord>();
    
array of all known activities for easy iterating.
 
     private final ArrayList<LocalActivityRecordmActivityArray
             = new ArrayList<LocalActivityRecord>();

    
True if only one activity can be resumed at a time
 
     private boolean mSingleMode;
    
    
Set to true once we find out the container is finishing.
 
     private boolean mFinishing;
    
    
Current state the owner (ActivityGroup) is in
 
     private int mCurState = ;
    
    
String ids of running activities starting with least recently used.
 
     // TODO: put back in stopping of activities.
     //private List<LocalActivityRecord>  mLRU = new ArrayList();
 
    
Create a new LocalActivityManager for holding activities running within the given parent.

Parameters:
parent the host of the embedded activities
singleMode True if the LocalActivityManger should keep a maximum of one activity resumed
    public LocalActivityManager(Activity parentboolean singleMode) {
         = ActivityThread.currentActivityThread();
         = parent;
         = singleMode;
    }
    private void moveToState(LocalActivityRecord rint desiredState) {
        if (r.curState ==  || r.curState == ) {
            // startActivity() has not yet been called, so nothing to do.
            return;
        }
        
        if (r.curState == ) {
            // Get the lastNonConfigurationInstance for the activity
            HashMap<String,ObjectlastNonConfigurationInstances =
                .getLastNonConfigurationChildInstances();
            Object instance = null;
            if (lastNonConfigurationInstances != null) {
                instance = lastNonConfigurationInstances.get(r.id);
            }
            
            // We need to have always created the activity.
            if () Log.v(r.id + ": starting " + r.intent);
            if (r.activityInfo == null) {
                r.activityInfo = .resolveActivityInfo(r.intent);
            }
            r.activity = .startActivityNow(
                    r.idr.intentr.activityInforr.instanceStateinstance);
            if (r.activity == null) {
                return;
            }
            r.window = r.activity.getWindow();
            r.instanceState = null;
            r.curState = ;
            
            if (desiredState == ) {
                if () Log.v(r.id + ": resuming");
                .performResumeActivity(rtrue);
                r.curState = ;
            }
            
            // Don't do anything more here.  There is an important case:
            // if this is being done as part of onCreate() of the group, then
            // the launching of the activity gets its state a little ahead
            // of our own (it is now STARTED, while we are only CREATED).
            // If we just leave things as-is, we'll deal with it as the
            // group's state catches up.
            return;
        }
        
        switch (r.curState) {
            case :
                if (desiredState == ) {
                    if () Log.v(r.id + ": restarting");
                    .performRestartActivity(r);
                    r.curState = ;
                }
                if (desiredState == ) {
                    if () Log.v(r.id + ": restarting and resuming");
                    .performRestartActivity(r);
                    .performResumeActivity(rtrue);
                    r.curState = ;
                }
                return;
                
            case :
                if (desiredState == ) {
                    // Need to resume it...
                    if () Log.v(r.id + ": resuming");
                    .performResumeActivity(rtrue);
                    r.instanceState = null;
                    r.curState = ;
                }
                if (desiredState == ) {
                    if () Log.v(r.id + ": stopping");
                    .performStopActivity(r);
                    r.curState = ;
                }
                return;
                
            case :
                if (desiredState == ) {
                    if () Log.v(r.id + ": pausing");
                    performPause(r);
                    r.curState = ;
                }
                if (desiredState == ) {
                    if () Log.v(r.id + ": pausing");
                    performPause(r);
                    if () Log.v(r.id + ": stopping");
                    .performStopActivity(r);
                    r.curState = ;
                }
                return;
        }
    }
    
    private void performPause(LocalActivityRecord rboolean finishing) {
        boolean needState = r.instanceState == null;
        Bundle instanceState = .performPauseActivity(r,
                finishingneedState);
        if (needState) {
            r.instanceState = instanceState;
        }
    }
    
    
Start a new activity running in the group. Every activity you start must have a unique string ID associated with it -- this is used to keep track of the activity, so that if you later call startActivity() again on it the same activity object will be retained.

When there had previously been an activity started under this id, it may either be destroyed and a new one started, or the current one re-used, based on these conditions, in order:

  • If the Intent maps to a different activity component than is currently running, the current activity is finished and a new one started.
  • If the current activity uses a non-multiple launch mode (such as singleTop), or the Intent has the android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP flag set, then the current activity will remain running and its Activity.onNewIntent() method called.
  • If the new Intent is the same (excluding extras) as the previous one, and the new Intent does not have the android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP set, then the current activity will remain running as-is.
  • Otherwise, the current activity will be finished and a new one started.

If the given Intent can not be resolved to an available Activity, this method throws android.content.ActivityNotFoundException.

Warning: There is an issue where, if the Intent does not include an explicit component, we can restore the state for a different activity class than was previously running when the state was saved (if the set of available activities changes between those points).

Parameters:
id Unique identifier of the activity to be started
intent The Intent describing the activity to be started
Returns:
Returns the window of the activity. The caller needs to take care of adding this window to a view hierarchy, and likewise dealing with removing the old window if the activity has changed.
Throws:
android.content.ActivityNotFoundException
    public Window startActivity(String idIntent intent) {
        if ( == ) {
            throw new IllegalStateException(
                    "Activities can't be added until the containing group has been created.");
        }
        
        boolean adding = false;
        boolean sameIntent = false;
        ActivityInfo aInfo = null;
        
        // Already have information about the new activity id?
        LocalActivityRecord r = .get(id);
        if (r == null) {
            // Need to create it...
            r = new LocalActivityRecord(idintent);
            adding = true;
        } else if (r.intent != null) {
            sameIntent = r.intent.filterEquals(intent); 
            if (sameIntent) {
                // We are starting the same activity.
                aInfo = r.activityInfo;
            }
        }
        if (aInfo == null) {
            aInfo = .resolveActivityInfo(intent);
        }
        
        // Pause the currently running activity if there is one and only a single
        // activity is allowed to be running at a time.
        if () {
            LocalActivityRecord old = ;
    
            // If there was a previous activity, and it is not the current
            // activity, we need to stop it.
            if (old != null && old != r &&  == ) {
                moveToState(old);
            }
        }
        if (adding) {
            // It's a brand new world.
            .put(idr);
            .add(r);
        } else if (r.activityInfo != null) {
            // If the new activity is the same as the current one, then
            // we may be able to reuse it.
            if (aInfo == r.activityInfo ||
                    (aInfo.name.equals(r.activityInfo.name) &&
                            aInfo.packageName.equals(r.activityInfo.packageName))) {
                if (aInfo.launchMode != . ||
                        (intent.getFlags()&.) != 0) {
                    // The activity wants onNewIntent() called.
                    ArrayList<Intentintents = new ArrayList<Intent>(1);
                    intents.add(intent);
                    if () Log.v(r.id + ": new intent");
                    .performNewIntents(rintents);
                    r.intent = intent;
                    moveToState(r);
                    if () {
                         = r;
                    }
                    return r.window;
                }
                if (sameIntent &&
                        (intent.getFlags()&.) == 0) {
                    // We are showing the same thing, so this activity is
                    // just resumed and stays as-is.
                    r.intent = intent;
                    moveToState(r);
                    if () {
                         = r;
                    }
                    return r.window;
                }
            }
            
            // The new activity is different than the current one, or it
            // is a multiple launch activity, so we need to destroy what
            // is currently there.
            performDestroy(rtrue);
        }
        
        r.intent = intent;
        r.curState = ;
        r.activityInfo = aInfo;
        moveToState(r);
        // When in single mode keep track of the current activity
        if () {
             = r;
        }
        return r.window;
    }
    private Window performDestroy(LocalActivityRecord rboolean finish) {
        Window win = null;
        win = r.window;
        if (r.curState ==  && !finish) {
            performPause(rfinish);
        }
        if () Log.v(r.id + ": destroying");
        .performDestroyActivity(rfinish);
        r.activity = null;
        r.window = null;
        if (finish) {
            r.instanceState = null;
        }
        r.curState = ;
        return win;
    }
    
    
Destroy the activity associated with a particular id. This activity will go through the normal lifecycle events and fine onDestroy(), and then the id removed from the group.

Parameters:
id Unique identifier of the activity to be destroyed
finish If true, this activity will be finished, so its id and all state are removed from the group.
Returns:
Returns the window that was used to display the activity, or null if there was none.
    public Window destroyActivity(String idboolean finish) {
        LocalActivityRecord r = .get(id);
        Window win = null;
        if (r != null) {
            win = performDestroy(rfinish);
            if (finish) {
                .remove(r);
            }
        }
        return win;
    }
    
    
Retrieve the Activity that is currently running.

Returns:
the currently running (resumed) Activity, or null if there is not one
See also:
startActivity(java.lang.String,android.content.Intent)
getCurrentId()
    public Activity getCurrentActivity() {
        return  != null ? . : null;
    }

    
Retrieve the ID of the activity that is currently running.

Returns:
the ID of the currently running (resumed) Activity, or null if there is not one
See also:
startActivity(java.lang.String,android.content.Intent)
getCurrentActivity()
    public String getCurrentId() {
        return  != null ? . : null;
    }

    
Return the Activity object associated with a string ID.

Returns:
the associated Activity object, or null if the id is unknown or its activity is not currently instantiated
See also:
startActivity(java.lang.String,android.content.Intent)
    public Activity getActivity(String id) {
        LocalActivityRecord r = .get(id);
        return r != null ? r.activity : null;
    }

    
Restore a state that was previously returned by saveInstanceState(). This adds to the activity group information about all activity IDs that had previously been saved, even if they have not been started yet, so if the user later navigates to them the correct state will be restored.

Note: This does not change the current running activity, or start whatever activity was previously running when the state was saved. That is up to the client to do, in whatever way it thinks is best.

Parameters:
state a previously saved state; does nothing if this is null
See also:
saveInstanceState()
    public void dispatchCreate(Bundle state) {
        if (state != null) {
            final Iterator<Stringi = state.keySet().iterator();
            while (i.hasNext()) {
                try {
                    final String id = i.next();
                    final Bundle astate = state.getBundle(id);
                    LocalActivityRecord r = .get(id);
                    if (r != null) {
                        r.instanceState = astate;
                    } else {
                        r = new LocalActivityRecord(idnull);
                        r.instanceState = astate;
                        .put(idr);
                        .add(r);
                    }
                } catch (Exception e) {
                    // Recover from -all- app errors.
                    Log.e(,
                          "Exception thrown when restoring LocalActivityManager state",
                          e);
                }
            }
        }
        
         = ;
    }

    
Retrieve the state of all activities known by the group. For activities that have previously run and are now stopped or finished, the last saved state is used. For the current running activity, its Activity.onSaveInstanceState(android.os.Bundle) is called to retrieve its current state.

Returns:
a Bundle holding the newly created state of all known activities
See also:
dispatchCreate(android.os.Bundle)
    public Bundle saveInstanceState() {
        Bundle state = null;
        // FIXME: child activities will freeze as part of onPaused. Do we
        // need to do this here?
        final int N = .size();
        for (int i=0; i<Ni++) {
            final LocalActivityRecord r = .get(i);
            if (state == null) {
                state = new Bundle();
            }
            if ((r.instanceState != null || r.curState == )
                    && r.activity != null) {
                // We need to save the state now, if we don't currently
                // already have it or the activity is currently resumed.
                final Bundle childState = new Bundle();
                r.activity.onSaveInstanceState(childState);
                r.instanceState = childState;
            }
            if (r.instanceState != null) {
                state.putBundle(r.idr.instanceState);
            }
        }
        return state;
    }

    
Called by the container activity in its Activity.onResume() so that LocalActivityManager can perform the corresponding action on the activities it holds.

    public void dispatchResume() {
         = ;
        if () {
            if ( != null) {
                moveToState();
            }
        } else {
            final int N = .size();
            for (int i=0; i<Ni++) {
                moveToState(.get(i), );
            }
        }
    }

    
Called by the container activity in its Activity.onPause() so that LocalActivityManager can perform the corresponding action on the activities it holds.

Parameters:
finishing set to true if the parent activity has been finished; this can be determined by calling Activity.isFinishing()
See also:
Activity.onPause()
Activity.isFinishing()
    public void dispatchPause(boolean finishing) {
        if (finishing) {
             = true;
        }
         = ;
        if () {
            if ( != null) {
                moveToState();
            }
        } else {
            final int N = .size();
            for (int i=0; i<Ni++) {
                LocalActivityRecord r = .get(i);
                if (r.curState == ) {
                    moveToState(r);
                }
            }
        }
    }

    
Called by the container activity in its Activity.onStop() so that LocalActivityManager can perform the corresponding action on the activities it holds.

    public void dispatchStop() {
         = ;
        final int N = .size();
        for (int i=0; i<Ni++) {
            LocalActivityRecord r = .get(i);
            moveToState(r);
        }
    }
    
    
Call onRetainNonConfigurationInstance on each child activity and store the results in a HashMap by id. Only construct the HashMap if there is a non-null object to store. Note that this does not support nested ActivityGroups.
        HashMap<String,ObjectinstanceMap = null;
        
        final int N = .size();
        for (int i=0; i<Ni++) {
            LocalActivityRecord r = .get(i);
            if ((r != null) && (r.activity != null)) {
                Object instance = r.activity.onRetainNonConfigurationInstance();
                if (instance != null) {
                    if (instanceMap == null) {
                        instanceMap = new HashMap<String,Object>();
                    }
                    instanceMap.put(r.idinstance);
                }
            }
        }
        return instanceMap;
    }

    
Remove all activities from this LocalActivityManager, performing an Activity.onDestroy() on any that are currently instantiated.
    public void removeAllActivities() {
        dispatchDestroy(true);
    }

    
Called by the container activity in its Activity.onDestroy() so that LocalActivityManager can perform the corresponding action on the activities it holds.

    public void dispatchDestroy(boolean finishing) {
        final int N = .size();
        for (int i=0; i<Ni++) {
            LocalActivityRecord r = .get(i);
            if () Log.v(r.id + ": destroying");
            .performDestroyActivity(rfinishing);
        }
        .clear();
        .clear();
    }
New to GrepCode? Check out our FAQ X