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(); } }
时间: 2024-02-02 09:02:32 浏览: 401
import java.io.*; public class FirstPart{ public static void main(String[] args) throws Exception{ System.out.print("The input Fahrenheit is "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int f = Integer.parseInt(br.re
5星 · 资源好评率100%
这是一个Java程序,它可以获取当前前台应用的包名和Activity名称,并启动一个目标应用并将其切换到前台。你可以将以下内容替换成你要启动的应用程序的包名和Activity名称:
```
String targetPackageName = "<target_package_name>";
String targetActivityName = "<target_activity_name>";
```
这个程序需要使用adb来启动应用程序并获取进程输出。确保你已经连接了Android设备,并且已经在计算机上安装了adb,并将adb添加到了系统路径中。
阅读全文