杀死自己的进程:
1.
android.os.Process.killProcess(android.os.Process.myPid());
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;
}