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