I can get a list of installed apps (both user and system apps). I am also able to uninstall user apps, however, not able to uninstall system apps.
Is there any way to uninstall system app?
If the phone is already rooted, will the following code work?
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:"+appPackageName.getText().toString()));
context.startActivity(intent);
you can execute root commands with:
runCommand("su");
runCommand("rm /data/system/application.package.apk");
runCommand("rm /data/data/application.package");
//when this doesn´t work try
runCommand("rm -r /data/system/application.package.apk");
runCommand("rm -r /data/data/application.package");
public static void runCommand(String command){
try {
Process chmod = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(chmod.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
chmod.waitFor();
outputString = output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
There is also a nice library: https://github.com/Free-Software-for-Android/RootCommands
You need to have root access in order to remove system or vendor apps.
$ su
# rm /data/system/application.package.apk
# rm /data/data/application.package
Try this on Rooted Device...it works
Process reboot = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(reboot.getOutputStream());
os.writeBytes("pm uninstall co.example.demo\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
reboot.waitFor();
Currently I have shell script commands which I run on android using terminal emulator application. Need to prepare an application to call the shell scripts from my android application show the result of the shell script on my application. Can anybody suggest the best way to do it.
Used code from here
public void runShellCommand(String[] cmds) throws Exception {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
InputStream is = p.getInputStream();
for (String temp : cmds) {
os.writeBytes(temp+"\n");
int read= 0;
byte[] buff = new byte[4096];
// if cmd requires an output
// due to the blocking behaviour of read(...)
boolean cmdRequiresAnOutput = true;
if (cmdRequiresAnOutput) {
while( is.available() <= 0) {
try { Thread.sleep(200); } catch(Exception ex) {}
}
while( is.available() > 0) {
read = is.read(buff);
if ( read <= 0 ) break;
String str = new String(buff,0,read);
console.println("#> "+str);
}
}
}
os.writeBytes("exit\n");
os.flush();
}
Sleep is required for commands that use long time.
I'm coding apps that use busybox binary library stored in my project's assets folder. In runtime I copy this library to /data/data/com.myapp/ folder, I make this file executable and than try to execute some util cmds that should be available from this binary lib. But I have not get desired result. I use next function:
private void shellCmd()
{
try {
Process process = null;
/* I used this to make the file executable */
// process = Runtime.getRuntime().exec("/system/bin/chmod 777 "
// + this.getFilesDir().getPath() + "/busybox");
// process = Runtime.getRuntime().exec("/system/bin/ls -l "
// + this.getFilesDir().getPath() + "/busybox");
/* this exec function doesnt execute(there is no prompt into logcat)*/
process = Runtime.getRuntime().exec( this.getFilesDir().getPath() + "/busybox ping -4 46.173.103.134");
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
Log.w("groupAB",output.toString());
Log.i("groupAB", "finish");
process.waitFor();
return;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
But when I'm trying to execute the same cmd using adb in way "adb shell /data/data/com.myapp/busybox ping -4 46.173.103.134" I get corect ping result. I'm confused why this doesn't work in a programming way. Where is my fault?
I am working on a program that needs to be able to determine what is on the android device at Xlocation. I am using "su ls Xlocation"
I want to get back and array list of files but only manage to get back the first Item. Am I missing a command that gets the next line? Or is there something else I need to do.
Below is my command I am sending
String[] commands = new String[]{"ls /system/app/"};
return doCommand(commands);
Below is my current method for doCommand
private boolean doCommand(String[] commands)
{
ArrayList<String> output = new ArrayList<String>();
boolean ran = false;
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
DataInputStream ins = new DataInputStream(process.getInputStream());
// This part works I sends the command right!
for (String single : commands)
{
os.writeBytes(single + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
process.waitFor();
ran = true;
}
int av = -1;
while (av != 0)
{
//////////////////////////// WORKING ON THIS TO GET ALL INFO /////////////////
av = ins.available();
if (av != 0)
{
byte[] b = new byte[av];
ins.read(b);
output.add(new String(b));
System.out.println(new String(b) + "Recieved form modem");
}
}
}
catch(Exception ex){}
return ran;
}
As seen currently it only returns true or false. However run in debug I only get the first item in output. (output = "[first.apk")
Edited Newer Version;
public ArrayList<String> doCommand(String[] commands)
{
ArrayList<String> output = new ArrayList<String>();
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
DataInputStream ins = new DataInputStream(process.getInputStream());
for (String single : commands)
{
os.writeBytes(single + "\n");
//os.flush();
output.add("true");
}
os.writeBytes("exit\n");
byte[] bc = new byte[10000];
String st = "";
while(ins.read(bc) != -1)
{
st += new String(bc);
os.flush();
}
output.add(st);
os.flush();
os.close();
ins.close();
process.waitFor();
}
catch(Exception ex)
{}
return output;
}
Now getting a decent amount of output but still not all where the directory has large items inside size limit of byte[10000] I have checked.
If anyone wants to improve on this and get an exact answer that works do so I still check this post.
Thanks
You can try adapting this method from my open source User Management (GitHub) app to do what you want. This will read each and every line of the output following a terminal command:
public static String[] getUserList()
{
Process p;
try {
p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()));
os.writeBytes("pm list-users"+"\n");
os.writeBytes("exit\n");
ArrayList<String> users = new ArrayList<String>();
String test;
bf.readLine();
while((test = bf.readLine()) != null)
{
users.add(test);
}
String[] userList = (String[]) users.toArray(new String[users.size()]);
os.flush();
return userList;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I'm a bit new to Java but I believe the issue is just a minor oversight.. ne in which I've run into a few times with Python ;)
Because you've added the below into your while loop:
os.writeBytes("exit\n");
os.flush();
After each iteration you are attempting to exit the terminal session. After the first iteration the terminal session would already be closed so this would explain why only the first result would be returned.
I would suggest adding the exit code after the while loop completes to ensure you are not sending the rest of the commands to a dead session. Alternatively you could recreate os during each iteration as well but that seems a bit redundant. ;)
Edit #1
I'm not familiar with the usage of bytes, but I have been able to parse the output of my commands with a similar while loop. I Also added stderr to the input to ensure the buffer is emptied when needed. Upon first glance at your new code, it appears you are defining a new String during each iteration of the while loop, instead of appending the line to a variable. This would cause your variable to be overwritten during each iteration. ;)
Below is some code I've used in the past to accomplish similar tasks. I quickly modified from my source but I am currently unable to give it a test run. Keep in mind that your os
is my stdout, and your ins is my stdin.
Runtime terminal = (Runtime) Runtime.getRuntime();
Process process = terminal.exec("su");
DataOutputStream stdout = new DataOutputStream(process.getOutputStream());
InputStream stderr = process.getErrorStream();
BufferedReader stdin = new BufferedReader(new InputStreamReader(stderr));
String line = "";
String output = "";
// Execute command and flush
stdout.writeBytes("your command here\n");
stdout.flush();
// Append stdin.readLine() to output variable until line is null
while ((line = stdin.readLine()) != null)
output += line;
// I've had mixed luck getting waitFor() to work, but technically it should force
// the shell to wait until the command completes. Uncomment it to try it out.
//process.waitFor();
stdout.writeBytes("exit\n");
stdout.flush();
// Print output to logcat
System.out.println(output);
For the life of me, I can't get my app to get the response from a process calling busybox from within su shell.
I've tried three different methods, as well as tried a combination of the three to get it to work, but I can never get the output from anything using busybox, only the rest of the commands.
To be more specific, I can get it to return commands like ls /data and cat suchandsuch.file, but anything that starts with "busybox" (i.e. busybox mount, busybox free) just won't show anything.
This was the method that got the closest for me, this code works with ls /data, but not "busybox free"
This one would run the command (for the most part), and return an empty string instead of loop endlessly from the inputstream.
Process p;
try {
p = Runtime.getRuntime().exec(new String[]{"su", "-c", "/system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
stdin.writeBytes("ls /data\n");
DataInputStream stdout = new DataInputStream(p.getInputStream());
byte[] buffer = new byte[4096];
int read = 0;
String out = new String();
while(true){
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<4096){
break;
}
}
Toast.makeText(getApplicationContext(), out, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
The toast near the bottom shows everything from ls /data, but when changed to anything for busybox, its blank or null.
I've also tried both of these, but neither of them worked. (I was passing the process to them after the command was run.)
Both of these would always result in the app freezing right when you hit the button for the methods.
String termReader(Process process){
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
try {
int i;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
reader.close();
return output.toString();
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
String processReader(Process process){
InputStream stdout = process.getInputStream();
byte[] buffer = new byte[1024];
int read;
String out = new String();
while(true){
try {
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<1024){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return out;
}
There's no stack traces to work with, so I'm starting to get a bit stumped.
Edited with the code proposed below, uhm, below :D
I changed it around a small bit to make it a oneclick run thing for easier troubleshooting and testing.
This also freezes when it tries to read the inputstream, and if I call stdin.writeBytes("exit\n") before trying to read the stream it gives me the blank answer from closing the terminal, if I call it after, it loops endlessly.
void Run() {
String command = "busybox traceroute\n";
StringBuffer theRun = null;
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream stdin = new DataOutputStream(process.getOutputStream());
stdin.writeBytes(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
theRun = output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Toast.makeText(getApplicationContext(), theRun, Toast.LENGTH_SHORT).show();
}
It seems like its skipping the first line (the busybox info line you get every time you invoke the command) and not catching the rest of the data. Ive tried all variations I can think of to get this working right :/
If anybody's got some insight on this, I'd be greatly appreciative :)
Here is a quick solution... It is a utility class I created just for this. You can use the native shell, a root shell if the device is rooted, or set a custom shell. Here you go.
https://github.com/jjNford/android-shell
I've found a sort of a workaround for this.
First of all, running commands linked to busybox in my case would never return their output through their InputStream, no matter what method I tried (And I tried ALOT lol).
This is what I found out I could do. It's a bit tedious, and doesn't give you the full output, but if you want something to rely on whether a command fired off properly (in my case, my app just wouldn't work right if I couldn't compare how everything ran.)
You cant get the input from the process, but you CAN get the exit value if you work it right :) this works for anything that doesn't give you a complex response (like using cat on a large file)
The difference between the two is easy to find, for instance:
command = "cat /sys" // works, exits with 1
command = "cat /init.rc" doesnt work, exits with 0
This is how I set it up to work easily. Run the commands as normal using the method provided by MasterJB:
process p;
try {
p = Runtime.getRuntime().exec(new String[]{"su", "-c", "/system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
stdin.writeBytes(command);
stdin.writeBytes("echo $?\n");
DataInputStream stdout = new DataInputStream(p.getInputStream());
byte[] buffer = new byte[4096];
int read = 0;
String out = new String();
while(true){
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<4096){
break;
}
// here is where you catch the error value
int len = out.length();
char suExitValue = out.charAt(len-2);
Toast.makeText(getApplicationContext(), String.valueOf(suExitValue), Toast.LENGTH_SHORT).show();
return0or1(Integer.valueOf(suExitValue), command); // 0 or 1 Method
// end catching exit value
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I also found it easier to make a "0 or 1" method to return what happened. In this example it's fired as a toast. You may also want to test if the char is actually an integer, as some commands give no exit value whatsoever (weird, I know. One instance is ls /sys, this returns a blank exit value when run through a su terminal.)
String return0or1 (int returnValue, String command){
String message = command + " - Cannot get return value.";
if (returnValue == 0){
message = command + " - successful.";
return message;
}
if (returnValue == 1){
message = command + " - failed.";
return message;
}
return message;
}
With a little bit of research you can match just about any exit value with proper responses, just gotta capture them right :)
These methods return just whether the command ran (0), but if it gets a double or triple char exit code, the last digit may be 0 when it failed (i.e. when exit value is 10), so this will work in most cases, but needs to be expanded upon to catch double and triple values.