1 /* 2 * Copyright 2022 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 com.google.snippet.uwb; 18 19 import android.app.UiAutomation; 20 import android.content.Context; 21 import android.uwb.UwbManager; 22 23 import androidx.test.platform.app.InstrumentationRegistry; 24 25 import com.google.android.mobly.snippet.Snippet; 26 import com.google.android.mobly.snippet.rpc.Rpc; 27 import com.google.android.mobly.snippet.util.Log; 28 29 import java.lang.reflect.Method; 30 31 /** Snippet class exposing Android APIs for Uwb. */ 32 public class UwbManagerSnippet implements Snippet { 33 private static class UwbManagerSnippetException extends Exception { 34 private static final long serialVersionUID = 1; 35 UwbManagerSnippetException(String msg)36 UwbManagerSnippetException(String msg) { 37 super(msg); 38 } 39 UwbManagerSnippetException(String msg, Throwable err)40 UwbManagerSnippetException(String msg, Throwable err) { 41 super(msg, err); 42 } 43 } 44 private final UwbManager mUwbManager; 45 private final Context mContext; 46 UwbManagerSnippet()47 public UwbManagerSnippet() throws Throwable { 48 mContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 49 mUwbManager = mContext.getSystemService(UwbManager.class); 50 adoptShellPermission(); 51 } 52 53 /** Get the UWB state. */ 54 @Rpc(description = "Get Uwb state") isUwbEnabled()55 public boolean isUwbEnabled() { 56 return mUwbManager.isUwbEnabled(); 57 } 58 59 /** Get the UWB state. */ 60 @Rpc(description = "Set Uwb state") setUwbEnabled(boolean enabled)61 public void setUwbEnabled(boolean enabled) { 62 mUwbManager.setUwbEnabled(enabled); 63 } 64 65 @Override shutdown()66 public void shutdown() {} 67 adoptShellPermission()68 private void adoptShellPermission() throws Throwable { 69 UiAutomation uia = InstrumentationRegistry.getInstrumentation().getUiAutomation(); 70 uia.adoptShellPermissionIdentity(); 71 try { 72 Class<?> cls = Class.forName("android.app.UiAutomation"); 73 Method destroyMethod = cls.getDeclaredMethod("destroy"); 74 destroyMethod.invoke(uia); 75 } catch (ReflectiveOperationException e) { 76 throw new UwbManagerSnippetException("Failed to cleaup Ui Automation", e); 77 } 78 } 79 } 80