TaskStackBuilder.java revision 9ceac5a02f08bc350d6047660ed75019313f4703
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.ComponentName;
20import android.content.Context;
21import android.content.Intent;
22import android.content.pm.ActivityInfo;
23import android.content.pm.PackageManager;
24import android.content.pm.PackageManager.NameNotFoundException;
25import android.os.Bundle;
26import android.util.Log;
27
28import java.util.ArrayList;
29
30/**
31 * Utility class for constructing synthetic back stacks for cross-task navigation
32 * on Android 3.0 and newer.
33 *
34 * <p>In API level 11 (Android 3.0/Honeycomb) the recommended conventions for
35 * app navigation using the back key changed. The back key's behavior is local
36 * to the current task and does not capture navigation across different tasks.
37 * Navigating across tasks and easily reaching the previous task is accomplished
38 * through the "recents" UI, accessible through the software-provided Recents key
39 * on the navigation or system bar. On devices with the older hardware button configuration
40 * the recents UI can be accessed with a long press on the Home key.</p>
41 *
42 * <p>When crossing from one task stack to another post-Android 3.0,
43 * the application should synthesize a back stack/history for the new task so that
44 * the user may navigate out of the new task and back to the Launcher by repeated
45 * presses of the back key. Back key presses should not navigate across task stacks.</p>
46 *
47 * <p>TaskStackBuilder provides a way to obey the correct conventions
48 * around cross-task navigation.</p>
49 *
50 * <div class="special reference">
51 * <h3>About Navigation</h3>
52 * For more detailed information about tasks, the back stack, and navigation design guidelines,
53 * please read
54 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
55 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
56 * from the design guide.
57 * </div>
58 */
59public class TaskStackBuilder {
60    private static final String TAG = "TaskStackBuilder";
61
62    private final ArrayList<Intent> mIntents = new ArrayList<Intent>();
63    private final Context mSourceContext;
64
65    private TaskStackBuilder(Context a) {
66        mSourceContext = a;
67    }
68
69    /**
70     * Return a new TaskStackBuilder for launching a fresh task stack consisting
71     * of a series of activities.
72     *
73     * @param context The context that will launch the new task stack or generate a PendingIntent
74     * @return A new TaskStackBuilder
75     */
76    public static TaskStackBuilder create(Context context) {
77        return new TaskStackBuilder(context);
78    }
79
80    /**
81     * Add a new Intent to the task stack. The most recently added Intent will invoke
82     * the Activity at the top of the final task stack.
83     *
84     * @param nextIntent Intent for the next Activity in the synthesized task stack
85     * @return This TaskStackBuilder for method chaining
86     */
87    public TaskStackBuilder addNextIntent(Intent nextIntent) {
88        mIntents.add(nextIntent);
89        return this;
90    }
91
92    /**
93     * Add a new Intent with the resolved chain of parents for the target activity to
94     * the task stack.
95     *
96     * <p>This is equivalent to calling {@link #addParentStack(ComponentName) addParentStack}
97     * with the resolved ComponentName of nextIntent (if it can be resolved), followed by
98     * {@link #addNextIntent(Intent) addNextIntent} with nextIntent.</p>
99     *
100     * @param nextIntent Intent for the topmost Activity in the synthesized task stack.
101     *                   Its chain of parents as specified in the manifest will be added.
102     * @return This TaskStackBuilder for method chaining.
103     */
104    public TaskStackBuilder addNextIntentWithParentStack(Intent nextIntent) {
105        ComponentName target = nextIntent.getComponent();
106        if (target == null) {
107            target = nextIntent.resolveActivity(mSourceContext.getPackageManager());
108        }
109        if (target != null) {
110            addParentStack(target);
111        }
112        addNextIntent(nextIntent);
113        return this;
114    }
115
116    /**
117     * Add the activity parent chain as specified by the
118     * {@link Activity#getParentActivityIntent() getParentActivityIntent()} method of the activity
119     * specified and the {@link android.R.attr#parentActivityName parentActivityName} attributes
120     * of each successive activity (or activity-alias) element in the application's manifest
121     * to the task stack builder.
122     *
123     * @param sourceActivity All parents of this activity will be added
124     * @return This TaskStackBuilder for method chaining
125     */
126    public TaskStackBuilder addParentStack(Activity sourceActivity) {
127        final Intent parent = sourceActivity.getParentActivityIntent();
128        if (parent != null) {
129            // We have the actual parent intent, build the rest from static metadata
130            // then add the direct parent intent to the end.
131            ComponentName target = parent.getComponent();
132            if (target == null) {
133                target = parent.resolveActivity(mSourceContext.getPackageManager());
134            }
135            addParentStack(target);
136            addNextIntent(parent);
137        }
138        return this;
139    }
140
141    /**
142     * Add the activity parent chain as specified by the
143     * {@link android.R.attr#parentActivityName parentActivityName} attribute of the activity
144     * (or activity-alias) element in the application's manifest to the task stack builder.
145     *
146     * @param sourceActivityClass All parents of this activity will be added
147     * @return This TaskStackBuilder for method chaining
148     */
149    public TaskStackBuilder addParentStack(Class<?> sourceActivityClass) {
150        return addParentStack(new ComponentName(mSourceContext, sourceActivityClass));
151    }
152
153    /**
154     * Add the activity parent chain as specified by the
155     * {@link android.R.attr#parentActivityName parentActivityName} attribute of the activity
156     * (or activity-alias) element in the application's manifest to the task stack builder.
157     *
158     * @param sourceActivityName Must specify an Activity component. All parents of
159     *                           this activity will be added
160     * @return This TaskStackBuilder for method chaining
161     */
162    public TaskStackBuilder addParentStack(ComponentName sourceActivityName) {
163        final int insertAt = mIntents.size();
164        PackageManager pm = mSourceContext.getPackageManager();
165        try {
166            ActivityInfo info = pm.getActivityInfo(sourceActivityName, 0);
167            String parentActivity = info.parentActivityName;
168            while (parentActivity != null) {
169                final ComponentName target = new ComponentName(info.packageName, parentActivity);
170                info = pm.getActivityInfo(target, 0);
171                parentActivity = info.parentActivityName;
172                final Intent parent = parentActivity == null && insertAt == 0
173                        ? Intent.makeMainActivity(target)
174                        : new Intent().setComponent(target);
175                mIntents.add(insertAt, parent);
176            }
177        } catch (NameNotFoundException e) {
178            Log.e(TAG, "Bad ComponentName while traversing activity parent metadata");
179            throw new IllegalArgumentException(e);
180        }
181        return this;
182    }
183
184    /**
185     * @return the number of intents added so far.
186     */
187    public int getIntentCount() {
188        return mIntents.size();
189    }
190
191    /**
192     * Return the intent at the specified index for modification.
193     * Useful if you need to modify the flags or extras of an intent that was previously added,
194     * for example with {@link #addParentStack(Activity)}.
195     *
196     * @param index Index from 0-getIntentCount()
197     * @return the intent at position index
198     */
199    public Intent editIntentAt(int index) {
200        return mIntents.get(index);
201    }
202
203    /**
204     * Start the task stack constructed by this builder.
205     */
206    public void startActivities() {
207        startActivities(null);
208    }
209
210    /**
211     * Start the task stack constructed by this builder.
212     *
213     * @param options Additional options for how the Activity should be started.
214     * See {@link android.content.Context#startActivity(Intent, Bundle)
215     * Context.startActivity(Intent, Bundle)} for more details.
216     */
217    public void startActivities(Bundle options) {
218        if (mIntents.isEmpty()) {
219            throw new IllegalStateException(
220                    "No intents added to TaskStackBuilder; cannot startActivities");
221        }
222
223        mSourceContext.startActivities(getIntents(), options);
224    }
225
226    /**
227     * Obtain a {@link PendingIntent} for launching the task constructed by this builder so far.
228     *
229     * @param requestCode Private request code for the sender
230     * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT},
231     *              {@link PendingIntent#FLAG_NO_CREATE}, {@link PendingIntent#FLAG_CANCEL_CURRENT},
232     *              {@link PendingIntent#FLAG_UPDATE_CURRENT}, or any of the flags supported by
233     *              {@link Intent#fillIn(Intent, int)} to control which unspecified parts of the
234     *              intent that can be supplied when the actual send happens.
235     *
236     * @return The obtained PendingIntent
237     */
238    public PendingIntent getPendingIntent(int requestCode, int flags) {
239        return getPendingIntent(requestCode, flags, null);
240    }
241
242    /**
243     * Obtain a {@link PendingIntent} for launching the task constructed by this builder so far.
244     *
245     * @param requestCode Private request code for the sender
246     * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT},
247     *              {@link PendingIntent#FLAG_NO_CREATE}, {@link PendingIntent#FLAG_CANCEL_CURRENT},
248     *              {@link PendingIntent#FLAG_UPDATE_CURRENT}, or any of the flags supported by
249     *              {@link Intent#fillIn(Intent, int)} to control which unspecified parts of the
250     *              intent that can be supplied when the actual send happens.
251     * @param options Additional options for how the Activity should be started.
252     * See {@link android.content.Context#startActivity(Intent, Bundle)
253     * Context.startActivity(Intent, Bundle)} for more details.
254     *
255     * @return The obtained PendingIntent
256     */
257    public PendingIntent getPendingIntent(int requestCode, int flags, Bundle options) {
258        if (mIntents.isEmpty()) {
259            throw new IllegalStateException(
260                    "No intents added to TaskStackBuilder; cannot getPendingIntent");
261        }
262
263        return PendingIntent.getActivities(mSourceContext, requestCode, getIntents(),
264                flags, options);
265    }
266
267    /**
268     * Return an array containing the intents added to this builder. The intent at the
269     * root of the task stack will appear as the first item in the array and the
270     * intent at the top of the stack will appear as the last item.
271     *
272     * @return An array containing the intents added to this builder.
273     */
274    public Intent[] getIntents() {
275        Intent[] intents = new Intent[mIntents.size()];
276        if (intents.length == 0) return intents;
277
278        intents[0] = new Intent(mIntents.get(0)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
279                Intent.FLAG_ACTIVITY_CLEAR_TASK |
280                Intent.FLAG_ACTIVITY_TASK_ON_HOME);
281        for (int i = 1; i < intents.length; i++) {
282            intents[i] = new Intent(mIntents.get(i));
283        }
284        return intents;
285    }
286}
287