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