TaskStackBuilder.java revision 56a1f598b89d0e65dbd2a2678b66a43f5b7638c2
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.support.v4.content.IntentCompat;
26import android.util.Log;
27
28import java.util.ArrayList;
29import java.util.Iterator;
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 backward-compatible way to obey the correct conventions
49 * around cross-task navigation on the device's version of the platform. On devices running
50 * Android 3.0 or newer, calls to the {@link #startActivities()} method or sending the
51 * {@link PendingIntent} generated by {@link #getPendingIntent(int, int)} will construct
52 * the synthetic back stack as prescribed. On devices running older versions of the platform,
53 * these same calls will invoke the topmost activity in the supplied stack, ignoring
54 * the rest of the synthetic stack and allowing the back key to navigate back to the previous
55 * task.</p>
56 *
57 * <div class="special reference">
58 * <h3>About Navigation</h3>
59 * For more detailed information about tasks, the back stack, and navigation design guidelines,
60 * please read
61 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
62 * from the developer guide and <a href="{@docRoot}design/patterns/navigation.html">Navigation</a>
63 * from the design guide.
64 * </div>
65 */
66public class TaskStackBuilder implements Iterable<Intent> {
67    private static final String TAG = "TaskStackBuilder";
68
69    interface TaskStackBuilderImpl {
70        PendingIntent getPendingIntent(Context context, Intent[] intents, int requestCode,
71                int flags);
72    }
73
74    static class TaskStackBuilderImplBase implements TaskStackBuilderImpl {
75        public PendingIntent getPendingIntent(Context context, Intent[] intents, int requestCode,
76                int flags) {
77            Intent topIntent = intents[intents.length - 1];
78            topIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
79            return PendingIntent.getActivity(context, requestCode, topIntent, flags);
80        }
81    }
82
83    static class TaskStackBuilderImplHoneycomb implements TaskStackBuilderImpl {
84        public PendingIntent getPendingIntent(Context context, Intent[] intents, int requestCode,
85                int flags) {
86            intents[0].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
87                    IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
88            return TaskStackBuilderHoneycomb.getActivitiesPendingIntent(context, requestCode,
89                    intents, flags);
90        }
91    }
92
93    private static final TaskStackBuilderImpl IMPL;
94
95    static {
96        if (Build.VERSION.SDK_INT >= 11) {
97            IMPL = new TaskStackBuilderImplHoneycomb();
98        } else {
99            IMPL = new TaskStackBuilderImplBase();
100        }
101    }
102
103    private final ArrayList<Intent> mIntents = new ArrayList<Intent>();
104    private final Context mSourceContext;
105
106    private TaskStackBuilder(Context a) {
107        mSourceContext = a;
108    }
109
110    /**
111     * Return a new TaskStackBuilder for launching a fresh task stack consisting
112     * of a series of activities.
113     *
114     * @param context The context that will launch the new task stack or generate a PendingIntent
115     * @return A new TaskStackBuilder
116     */
117    public static TaskStackBuilder from(Context context) {
118        return new TaskStackBuilder(context);
119    }
120
121    /**
122     * Add a new Intent to the task stack. The most recently added Intent will invoke
123     * the Activity at the top of the final task stack.
124     *
125     * @param nextIntent Intent for the next Activity in the synthesized task stack
126     * @return This TaskStackBuilder for method chaining
127     */
128    public TaskStackBuilder addNextIntent(Intent nextIntent) {
129        mIntents.add(nextIntent);
130        return this;
131    }
132
133    /**
134     * Add the activity parent chain as specified by manifest &lt;meta-data&gt; elements
135     * to the task stack builder.
136     *
137     * @param sourceActivity All parents of this activity will be added
138     * @return This TaskStackBuilder for method chaining
139     */
140    public TaskStackBuilder addParentStack(Activity sourceActivity) {
141        final int insertAt = mIntents.size();
142        Intent parent = NavUtils.getParentActivityIntent(sourceActivity);
143        while (parent != null) {
144            mIntents.add(insertAt, parent);
145            try {
146                parent = NavUtils.getParentActivityIntent(sourceActivity, parent.getComponent());
147            } catch (NameNotFoundException e) {
148                Log.e(TAG, "Bad ComponentName while traversing activity parent metadata");
149                throw new IllegalArgumentException(e);
150            }
151        }
152        return this;
153    }
154
155    /**
156     * Add the activity parent chain as specified by manifest &lt;meta-data&gt; elements
157     * to the task stack builder.
158     *
159     * @param sourceActivityClass All parents of this activity will be added
160     * @return This TaskStackBuilder for method chaining
161     */
162    public TaskStackBuilder addParentStack(Class<?> sourceActivityClass) {
163        final int insertAt = mIntents.size();
164        try {
165            Intent parent = NavUtils.getParentActivityIntent(mSourceContext, sourceActivityClass);
166            while (parent != null) {
167                mIntents.add(insertAt, parent);
168                parent = NavUtils.getParentActivityIntent(mSourceContext, parent.getComponent());
169            }
170        } catch (NameNotFoundException e) {
171            Log.e(TAG, "Bad ComponentName while traversing activity parent metadata");
172            throw new IllegalArgumentException(e);
173        }
174        return this;
175    }
176
177    /**
178     * @return the number of intents added so far.
179     */
180    public int getIntentCount() {
181        return mIntents.size();
182    }
183
184    /**
185     * Get the intent at the specified index.
186     * Useful if you need to modify the flags or extras of an intent that was previously added,
187     * for example with {@link #addParentStack(Activity)}.
188     *
189     * @param index Index from 0-getIntentCount()
190     * @return the intent at position index
191     */
192    public Intent getIntent(int index) {
193        return mIntents.get(index);
194    }
195
196    public Iterator<Intent> iterator() {
197        return mIntents.iterator();
198    }
199
200    /**
201     * Start the task stack constructed by this builder. The Context used to obtain
202     * this builder must be an Activity.
203     *
204     * <p>On devices that do not support API level 11 or higher the topmost activity
205     * will be started as a new task. On devices that do support API level 11 or higher
206     * the new task stack will be created in its entirety.</p>
207     */
208    public void startActivities() {
209        if (mIntents.isEmpty()) {
210            throw new IllegalStateException(
211                    "No intents added to TaskStackBuilder; cannot startActivities");
212        }
213
214        Intent[] intents = mIntents.toArray(new Intent[mIntents.size()]);
215        intents[0].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
216                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK |
217                IntentCompat.FLAG_ACTIVITY_TASK_ON_HOME);
218        if (!ActivityCompat.startActivities((Activity) mSourceContext, intents)) {
219            Intent topIntent = intents[intents.length - 1];
220            topIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
221            mSourceContext.startActivity(topIntent);
222        }
223    }
224
225    /**
226     * Obtain a {@link PendingIntent} for launching the task constructed by this builder so far.
227     *
228     * @param requestCode Private request code for the sender
229     * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT},
230     *              {@link PendingIntent#FLAG_NO_CREATE}, {@link PendingIntent#FLAG_CANCEL_CURRENT},
231     *              {@link PendingIntent#FLAG_UPDATE_CURRENT}, or any of the flags supported by
232     *              {@link Intent#fillIn(Intent, int)} to control which unspecified parts of the
233     *              intent that can be supplied when the actual send happens.
234     * @return The obtained PendingIntent
235     */
236    public PendingIntent getPendingIntent(int requestCode, int flags) {
237        if (mIntents.isEmpty()) {
238            throw new IllegalStateException(
239                    "No intents added to TaskStackBuilder; cannot getPendingIntent");
240        }
241
242        Intent[] intents = mIntents.toArray(new Intent[mIntents.size()]);
243        intents[0].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
244                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK |
245                IntentCompat.FLAG_ACTIVITY_TASK_ON_HOME);
246        return IMPL.getPendingIntent(mSourceContext, intents, requestCode, flags);
247    }
248}
249