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.Bundle; 26 import android.util.Log; 27 28 import androidx.core.content.ContextCompat; 29 30 import org.jspecify.annotations.NonNull; 31 import org.jspecify.annotations.Nullable; 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 * ### About Navigation 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 { getSupportParentActivityIntent()75 @Nullable Intent getSupportParentActivityIntent(); 76 } 77 78 private final ArrayList<Intent> mIntents = new ArrayList<>(); 79 private final Context mSourceContext; 80 TaskStackBuilder(Context a)81 private TaskStackBuilder(Context a) { 82 mSourceContext = a; 83 } 84 85 /** 86 * Return a new TaskStackBuilder for launching a fresh task stack consisting 87 * of a series of activities. 88 * 89 * @param context The context that will launch the new task stack or generate a PendingIntent 90 * @return A new TaskStackBuilder 91 */ create(@onNull Context context)92 public static @NonNull TaskStackBuilder create(@NonNull Context context) { 93 return new TaskStackBuilder(context); 94 } 95 96 /** 97 * Return a new TaskStackBuilder for launching a fresh task stack consisting 98 * of a series of activities. 99 * 100 * @param context The context that will launch the new task stack or generate a PendingIntent 101 * @return A new TaskStackBuilder 102 * 103 * @deprecated use {@link #create(Context)} instead 104 */ 105 @Deprecated from(Context context)106 public static TaskStackBuilder from(Context context) { 107 return create(context); 108 } 109 110 /** 111 * Add a new Intent to the task stack. The most recently added Intent will invoke 112 * the Activity at the top of the final task stack. 113 * 114 * @param nextIntent Intent for the next Activity in the synthesized task stack 115 * @return This TaskStackBuilder for method chaining 116 */ addNextIntent(@onNull Intent nextIntent)117 public @NonNull TaskStackBuilder addNextIntent(@NonNull Intent nextIntent) { 118 mIntents.add(nextIntent); 119 return this; 120 } 121 122 /** 123 * Add a new Intent with the resolved chain of parents for the target activity to 124 * the task stack. 125 * 126 * <p>This is equivalent to calling {@link #addParentStack(ComponentName) addParentStack} 127 * with the resolved ComponentName of nextIntent (if it can be resolved), followed by 128 * {@link #addNextIntent(Intent) addNextIntent} with nextIntent.</p> 129 * 130 * @param nextIntent Intent for the topmost Activity in the synthesized task stack. 131 * Its chain of parents as specified in the manifest will be added. 132 * @return This TaskStackBuilder for method chaining. 133 */ addNextIntentWithParentStack(@onNull Intent nextIntent)134 public @NonNull TaskStackBuilder addNextIntentWithParentStack(@NonNull Intent nextIntent) { 135 ComponentName target = nextIntent.getComponent(); 136 if (target == null) { 137 target = nextIntent.resolveActivity(mSourceContext.getPackageManager()); 138 } 139 if (target != null) { 140 addParentStack(target); 141 } 142 addNextIntent(nextIntent); 143 return this; 144 } 145 146 /** 147 * Add the activity parent chain as specified by manifest <meta-data> elements 148 * to the task stack builder. 149 * 150 * @param sourceActivity All parents of this activity will be added 151 * @return This TaskStackBuilder for method chaining 152 */ addParentStack(@onNull Activity sourceActivity)153 public @NonNull TaskStackBuilder addParentStack(@NonNull Activity sourceActivity) { 154 Intent parent = null; 155 if (sourceActivity instanceof SupportParentable) { 156 parent = ((SupportParentable) sourceActivity).getSupportParentActivityIntent(); 157 } 158 if (parent == null) { 159 parent = NavUtils.getParentActivityIntent(sourceActivity); 160 } 161 162 if (parent != null) { 163 // We have the actual parent intent, build the rest from static metadata 164 // then add the direct parent intent to the end. 165 ComponentName target = parent.getComponent(); 166 if (target == null) { 167 target = parent.resolveActivity(mSourceContext.getPackageManager()); 168 } 169 addParentStack(target); 170 addNextIntent(parent); 171 } 172 return this; 173 } 174 175 /** 176 * Add the activity parent chain as specified by manifest <meta-data> elements 177 * to the task stack builder. 178 * 179 * @param sourceActivityClass All parents of this activity will be added 180 * @return This TaskStackBuilder for method chaining 181 */ addParentStack(@onNull Class<?> sourceActivityClass)182 public @NonNull TaskStackBuilder addParentStack(@NonNull Class<?> sourceActivityClass) { 183 return addParentStack(new ComponentName(mSourceContext, sourceActivityClass)); 184 } 185 186 /** 187 * Add the activity parent chain as specified by manifest <meta-data> elements 188 * to the task stack builder. 189 * 190 * @param sourceActivityName Must specify an Activity component. All parents of 191 * this activity will be added 192 * @return This TaskStackBuilder for method chaining 193 */ addParentStack(@onNull ComponentName sourceActivityName)194 public @NonNull TaskStackBuilder addParentStack(@NonNull ComponentName sourceActivityName) { 195 final int insertAt = mIntents.size(); 196 try { 197 Intent parent = NavUtils.getParentActivityIntent(mSourceContext, sourceActivityName); 198 while (parent != null) { 199 mIntents.add(insertAt, parent); 200 parent = NavUtils.getParentActivityIntent(mSourceContext, parent.getComponent()); 201 } 202 } catch (NameNotFoundException e) { 203 Log.e(TAG, "Bad ComponentName while traversing activity parent metadata"); 204 throw new IllegalArgumentException(e); 205 } 206 return this; 207 } 208 209 /** 210 * @return the number of intents added so far. 211 */ getIntentCount()212 public int getIntentCount() { 213 return mIntents.size(); 214 } 215 216 /** 217 * Get the intent at the specified index. 218 * Useful if you need to modify the flags or extras of an intent that was previously added, 219 * for example with {@link #addParentStack(Activity)}. 220 * 221 * @param index Index from 0-getIntentCount() 222 * @return the intent at position index 223 * 224 * @deprecated Renamed to editIntentAt to better reflect intended usage 225 */ 226 @Deprecated getIntent(int index)227 public Intent getIntent(int index) { 228 return editIntentAt(index); 229 } 230 231 /** 232 * Return the intent at the specified index for modification. 233 * Useful if you need to modify the flags or extras of an intent that was previously added, 234 * for example with {@link #addParentStack(Activity)}. 235 * 236 * @param index Index from 0-getIntentCount() 237 * @return the intent at position index 238 */ editIntentAt(int index)239 public @Nullable Intent editIntentAt(int index) { 240 return mIntents.get(index); 241 } 242 243 /** 244 * @deprecated Use editIntentAt instead 245 */ 246 @Override 247 @Deprecated iterator()248 public @NonNull Iterator<Intent> iterator() { 249 return mIntents.iterator(); 250 } 251 252 /** 253 * Start the task stack constructed by this builder. The Context used to obtain 254 * this builder must be an Activity. 255 * 256 * <p>On devices that do not support API level 11 or higher the topmost activity 257 * will be started as a new task. On devices that do support API level 11 or higher 258 * the new task stack will be created in its entirety.</p> 259 */ startActivities()260 public void startActivities() { 261 startActivities(null); 262 } 263 264 /** 265 * Start the task stack constructed by this builder. The Context used to obtain 266 * this builder must be an Activity. 267 * 268 * <p>On devices that do not support API level 11 or higher the topmost activity 269 * will be started as a new task. On devices that do support API level 11 or higher 270 * the new task stack will be created in its entirety.</p> 271 * 272 * @param options Additional options for how the Activity should be started. 273 * See {@link android.content.Context#startActivity(Intent, Bundle)} 274 */ startActivities(@ullable Bundle options)275 public void startActivities(@Nullable Bundle options) { 276 if (mIntents.isEmpty()) { 277 throw new IllegalStateException( 278 "No intents added to TaskStackBuilder; cannot startActivities"); 279 } 280 281 Intent[] intents = mIntents.toArray(new Intent[0]); 282 intents[0] = new Intent(intents[0]).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 283 | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); 284 if (!ContextCompat.startActivities(mSourceContext, intents, options)) { 285 Intent topIntent = new Intent(intents[intents.length - 1]); 286 topIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 287 mSourceContext.startActivity(topIntent); 288 } 289 } 290 291 /** 292 * Obtain a {@link PendingIntent} for launching the task constructed by this builder so far. 293 * 294 * @param requestCode Private request code for the sender 295 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT}, 296 * {@link PendingIntent#FLAG_NO_CREATE}, {@link PendingIntent#FLAG_CANCEL_CURRENT}, 297 * {@link PendingIntent#FLAG_UPDATE_CURRENT}, or any of the flags supported by 298 * {@link Intent#fillIn(Intent, int)} to control which unspecified parts of the 299 * intent that can be supplied when the actual send happens. 300 * @return The obtained PendingIntent. May return null only if 301 * {@link PendingIntent#FLAG_NO_CREATE} has been supplied. 302 */ getPendingIntent(int requestCode, int flags)303 public @Nullable PendingIntent getPendingIntent(int requestCode, int flags) { 304 return getPendingIntent(requestCode, flags, null); 305 } 306 307 /** 308 * Obtains a {@link PendingIntent} with mandatory mutability flag set on supported platform 309 * versions. The caller provides the flag as combination of all the other values except 310 * mutability flag. This method combines mutability flag when necessary. See {@link 311 * TaskStackBuilder#getPendingIntent(int, int)}. 312 */ getPendingIntent( int requestCode, int flags, boolean isMutable)313 public @Nullable PendingIntent getPendingIntent( 314 int requestCode, 315 int flags, 316 boolean isMutable) { 317 return getPendingIntent( 318 requestCode, 319 PendingIntentCompat.addMutabilityFlags(isMutable, flags)); 320 } 321 322 /** 323 * Obtain a {@link PendingIntent} for launching the task constructed by this builder so far. 324 * 325 * @param requestCode Private request code for the sender 326 * @param flags May be {@link PendingIntent#FLAG_ONE_SHOT}, 327 * {@link PendingIntent#FLAG_NO_CREATE}, {@link PendingIntent#FLAG_CANCEL_CURRENT}, 328 * {@link PendingIntent#FLAG_UPDATE_CURRENT}, or any of the flags supported by 329 * {@link Intent#fillIn(Intent, int)} to control which unspecified parts of the 330 * intent that can be supplied when the actual send happens. 331 * @param options Additional options for how the Activity should be started. 332 * See {@link android.content.Context#startActivity(Intent, Bundle)} 333 * @return The obtained PendingIntent. May return null only if 334 * {@link PendingIntent#FLAG_NO_CREATE} has been supplied. 335 */ getPendingIntent(int requestCode, int flags, @Nullable Bundle options)336 public @Nullable PendingIntent getPendingIntent(int requestCode, int flags, 337 @Nullable Bundle options) { 338 if (mIntents.isEmpty()) { 339 throw new IllegalStateException( 340 "No intents added to TaskStackBuilder; cannot getPendingIntent"); 341 } 342 343 Intent[] intents = mIntents.toArray(new Intent[0]); 344 intents[0] = new Intent(intents[0]).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 345 | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); 346 347 return PendingIntent.getActivities(mSourceContext, requestCode, intents, flags, options); 348 } 349 350 /** 351 * Obtains a {@link PendingIntent} with mandatory mutability flag set on supported platform 352 * versions. The caller provides the flag as combination of all the other values except 353 * mutability flag. This method combines mutability flag when necessary. See {@link 354 * TaskStackBuilder#getPendingIntent(int, int, Bundle)}. 355 */ getPendingIntent( int requestCode, int flags, @Nullable Bundle options, boolean isMutable)356 public @Nullable PendingIntent getPendingIntent( 357 int requestCode, 358 int flags, 359 @Nullable Bundle options, 360 boolean isMutable) { 361 return getPendingIntent( 362 requestCode, 363 PendingIntentCompat.addMutabilityFlags(isMutable, flags), 364 options); 365 } 366 367 /** 368 * Return an array containing the intents added to this builder. The intent at the 369 * root of the task stack will appear as the first item in the array and the 370 * intent at the top of the stack will appear as the last item. 371 * 372 * @return An array containing the intents added to this builder. 373 */ getIntents()374 public Intent @NonNull [] getIntents() { 375 Intent[] intents = new Intent[mIntents.size()]; 376 if (intents.length == 0) return intents; 377 378 intents[0] = new Intent(mIntents.get(0)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 379 | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME); 380 for (int i = 1; i < intents.length; i++) { 381 intents[i] = new Intent(mIntents.get(i)); 382 } 383 return intents; 384 } 385 } 386