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