是上面的脚本写成Android12的
时间: 2024-02-26 14:58:46 浏览: 241
Android 12 也可以使用类似的脚本来切换前台应用。以下是一个示例脚本:
```java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// 获取当前前台应用的包名和 Activity 名称
String[] currentFocus = getFocusedApp();
String packageName = currentFocus[0];
String activityName = currentFocus[1];
System.out.println("当前前台应用的包名:" + packageName);
System.out.println("当前前台应用的 Activity 名称:" + activityName);
// 启动目标应用并将其切换到前台
String targetPackageName = "<target_package_name>";
String targetActivityName = "<target_activity_name>";
startApp(targetPackageName, targetActivityName);
System.out.println("已切换到目标应用:" + targetPackageName + "/" + targetActivityName);
}
/**
* 获取当前前台应用的包名和 Activity 名称
*/
private static String[] getFocusedApp() {
String[] result = new String[2];
try {
Process process = Runtime.getRuntime().exec("dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'");
String output = readProcessOutput(process);
String[] lines = output.split("\n");
String currentFocusLine = lines[0];
String focusedAppLine = lines[1];
String[] currentFocus = currentFocusLine.split(" ");
String[] focusedApp = focusedAppLine.split(" ");
String packageName = currentFocus[4].split("/")[0];
String activityName = currentFocus[4].split("/")[1];
result[0] = packageName;
result[1] = activityName;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 启动应用并将其切换到前台
*/
private static void startApp(String packageName, String activityName) {
try {
Process process = Runtime.getRuntime().exec("adb shell am start -n " + packageName + "/" + activityName);
readProcessOutput(process);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取进程的输出结果
*/
private static String readProcessOutput(Process process) {
StringBuilder output = new StringBuilder();
try {
process.waitFor();
java.io.InputStream inputStream = process.getInputStream();
java.util.Scanner scanner = new java.util.Scanner(inputStream).useDelimiter("\\A");
if (scanner.hasNext()) {
String out = scanner.next();
output.append(out);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return output.toString();
}
}
```
这个 Java 代码可以通过 Android Studio 或其他 Java IDE 编译并运行,也可以通过命令行工具 javac 和 java 进行编译和运行。这个代码会先获取当前前台应用的包名和 Activity 名称,并输出到终端。然后,它会启动目标应用并将其切换到前台,并输出切换结果到终端。
阅读全文