Reputation: 183
I have an app, where user can list all running tasks in system, and also can kill some if he wants.
My code here:
public void killProcess(String PID) {
try {
Process p = Runtime.getRuntime().exec("/system/bin/kill " + PID);
Toast.makeText(getBaseContext(), "Process has been killed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getBaseContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
This works for me, but only when application can be killed by normal user, I have not granted the app a superuser permission and I don't want to, what I want is, to get a message Permission denied
or Operation not permitted
when normal user can't kill it. That's all. Any ideas ho to get this done properly?
I've seen also Process.killProcess(int PID)
can be used as it is an android's method, but don't know how to get an exception here either.
Thanks
EDITED
working code:
public void killProcess(String PID) {
try {
Process p = Runtime.getRuntime().exec("/system/bin/kill " + PID);
p.waitFor();
if (p.waitFor()==0){
Toast.makeText(getBaseContext(), "Process: " + PID + " has been killed.", Toast.LENGTH_SHORT).show();
} else Toast.makeText(getBaseContext(), "Argument must be process ID or kill process: " + PID + " is not permitted.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
Upvotes: 1
Views: 843
Reputation: 40508
You can use p.getErrorStream()
to read any error messages your kill Process
prints to stderr. You can also check the return value of p.waitFor()
to see if the command succeeded (0) or failed (otherwise).
Upvotes: 1