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