android中通過adb shell關閉和啓動應用

1.終端上:
a.首先我們需要來到sdk/adb目錄下;
b.執行“adb connect 192.168.1.xx”連接到你的設備,‘xx’表示你設備的ip;
c.執行“adb shell ps ”查看進程目錄;
d.找到你要關閉或者打開的應用包名,然後執行“adb shell am force-stop 包名”強制關閉或者“adb shell am start -n 包名/啓動類的名稱”;

2.程序中:

1.在代碼中
        try {
                    //關閉其他應用
                    Process exec = Runtime.getRuntime().exec("adb shell am force-stop 包名");
                    //打開其他應用
//                    Process exec = Runtime.getRuntime().exec("adb shell am start -n 包名/啓動類名稱");
                    if (exec.waitFor() == 0) {
                        Toast.makeText(MainActivity.this, "ok", 1).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
2.在manifest.xml加上權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>

如果說要徹底關閉當前應用,最好是用kill pid方式,如果用activity.finish()方式不是太好,代碼如下:

int pid = android.os.Process.myPid();
String command = "kill -9 "+ pid;
try {
    Runtime.getRuntime().exec(command);
} catch (IOException e) {
    e.printStackTrace();
}


如果你不想通過adb退出,那麼通過代碼也是可以退出應用的,以下代碼是關閉所有activity只保留目標activity:
Intent startMain = new Intent(context, LoginActivity.class);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startMain.addCategory(Intent.ACTION_MAIN);
        context.startActivity(startMain);
        System.exit(0);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章