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);
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值