1 /* 2 * Copyright 2025 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.test.uiautomator.internal 18 19 import android.app.ActivityManager 20 import android.content.ComponentName 21 import android.content.Context 22 import android.content.Intent 23 24 /** Manages operations related to starting and stopping an app. */ 25 internal class AppManager(private val context: Context) { 26 27 private val packageManager = context.packageManager 28 private val activityManager = 29 context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager 30 startAppnull31 fun startApp(packageName: String) { 32 var intent = packageManager.getLaunchIntentForPackage(packageName) 33 if (intent == null) { 34 intent = packageManager.getLeanbackLaunchIntentForPackage(packageName) 35 } 36 if (intent == null) { 37 intent = Intent(Intent.ACTION_MAIN).apply { setPackage(packageName) } 38 val resolveInfo = packageManager.resolveActivity(intent, 0) 39 if (resolveInfo != null && resolveInfo.activityInfo != null) { 40 intent.setComponent( 41 ComponentName( 42 resolveInfo.activityInfo.packageName, 43 resolveInfo.activityInfo.name 44 ) 45 ) 46 } 47 } 48 49 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 50 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) 51 52 context.startActivity(intent) 53 } 54 startActivitynull55 fun startActivity(packageName: String, activityName: String) { 56 val intent = 57 Intent().apply { 58 setComponent(ComponentName(packageName, activityName)) 59 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 60 addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) 61 } 62 context.startActivity(intent) 63 } 64 startActivitynull65 fun startActivity(clazz: Class<*>) { 66 val intent = 67 Intent().apply { 68 setClass(instrumentation.targetContext.applicationContext, clazz) 69 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 70 addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) 71 } 72 context.startActivity(intent) 73 } 74 startIntentnull75 fun startIntent(intent: Intent) { 76 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 77 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) 78 context.startActivity(intent) 79 } 80 clearAppDatanull81 fun clearAppData() { 82 activityManager.clearApplicationUserData() 83 } 84 } 85