如何kill一个App进程

杀死自己的进程:

1.

android.os.Process.killProcess(android.os.Process.myPid());


2.
System.exit(0);

杀死别人的进程:


1.参数是目标应用的包名,需要权限,但这个方法有时杀不死进程,正确的说是进程被杀死后,又重新启动了,真正杀死进程我推选第二种方法


<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.killBackgroundProcesses("com.android.mms");

 

2.说起来也郁闷,公司开发刚好遇到这个问题,摸索了好久才找到如下解决方法,需要root权限

public void killApp2(Context context, String packageName) {
	String command = "am force-stop " + packageName + "\n";
	sendShell(command);
}


public static String sendShell(String command) {
		Process proc = null;
		DataOutputStream os = null;
		BufferedReader in = null;
		InputStream error = null;
		InputStream input = null;
		try {
			Runtime runtime = Runtime.getRuntime();
			proc = runtime.exec("su\n");
			String line = "";
			os = new DataOutputStream(proc.getOutputStream());
			os.write((command + "\n").getBytes());
			os.writeBytes("exit\n");
			os.flush();
			proc.waitFor();
			// 拿到输出流,开始读取
			input = proc.getInputStream();
			error = proc.getErrorStream();
			int length = input.available();
			int errorLength = error.available();
			if (length > 0 && errorLength == 0) {
				// 执行正确
				in = new BufferedReader(new InputStreamReader(input));
				StringBuffer stringBuffer = new StringBuffer();
				while ((line = in.readLine()) != null) {
					stringBuffer.append(line + "\n");
					System.out.println("line:" + line);
				}
				line = stringBuffer.toString();
			}
			return line;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (in != null) {
					in.close();
				}
				if (error != null) {
					error.close();
				}
				if (input != null) {
					input.close();
				}
				if (proc != null) {
					proc.destroy();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值