1 /* 2 * Copyright (C) 2023 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 package com.android.launcher3.util.rule; 17 18 import android.app.UiAutomation; 19 import android.content.ComponentName; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.ServiceConnection; 23 import android.os.IBinder; 24 import android.util.Log; 25 26 import androidx.annotation.NonNull; 27 import androidx.test.platform.app.InstrumentationRegistry; 28 29 import org.junit.rules.TestRule; 30 import org.junit.runner.Description; 31 import org.junit.runners.model.Statement; 32 33 public class TISBindRule implements TestRule { 34 public static String TAG = "TISBindRule"; 35 public static String INTENT_FILTER = "android.intent.action.QUICKSTEP_SERVICE"; 36 public static String TIS_PERMISSIONS = "android.permission.STATUS_BAR_SERVICE"; 37 getLauncherPackageName(Context context)38 private String getLauncherPackageName(Context context) { 39 return ComponentName.unflattenFromString(context.getString( 40 com.android.internal.R.string.config_recentsComponentName)).getPackageName(); 41 } 42 createConnection()43 private ServiceConnection createConnection() { 44 return new ServiceConnection() { 45 @Override 46 public void onServiceConnected(ComponentName componentName, IBinder iBinder) { 47 Log.d(TAG, "Connected to TouchInteractionService"); 48 } 49 50 @Override 51 public void onServiceDisconnected(ComponentName componentName) { 52 Log.d(TAG, "Disconnected from TouchInteractionService"); 53 } 54 }; 55 } 56 57 @NonNull 58 @Override 59 public Statement apply(@NonNull Statement base, @NonNull Description description) { 60 return new Statement() { 61 62 @Override 63 public void evaluate() throws Throwable { 64 Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); 65 final ServiceConnection connection = createConnection(); 66 UiAutomation uiAutomation = 67 InstrumentationRegistry.getInstrumentation().getUiAutomation(); 68 uiAutomation.adoptShellPermissionIdentity(TIS_PERMISSIONS); 69 Intent launchIntent = new Intent(INTENT_FILTER); 70 launchIntent.setPackage(getLauncherPackageName(context)); 71 context.bindService(launchIntent, connection, Context.BIND_AUTO_CREATE); 72 uiAutomation.dropShellPermissionIdentity(); 73 try { 74 base.evaluate(); 75 } finally { 76 context.unbindService(connection); 77 } 78 } 79 }; 80 } 81 } 82