I am trying to execute 'top' command with following code which is working correctly:
try {
Process proc = Runtime.getRuntime().exec("top");
InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 500);
StringBuilder output = new StringBuilder();
String line = "";
int count = 0;
while ((line = reader.readLine()) != null) {
if(line.trim().equals(""))
continue;
if (line.trim().startsWith("User")) {
count++;
if (count > 2)
break; //'top' command keeps repeating call to itself. we need to stop after 1 call
}
if (line.contains("PID")) {
mainInfo.append(output.toString());
output.delete(0,output.length());
continue;
}
output.append(line)
.append(CPUInfoUtil.SEPARATOR_LINE); //append this separator to help parsing
}
reader.close();
proc.destroy();
return output.toString();
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
This is returning me all processes including kernel/root processes. I want to get only system processes except woner=root. For that I tried following 'top' with following options, which didn't work:
Process proc = Runtime.getRuntime().exec(new String[]{"top","U","!root"});
I know I can also get running processes using following code but it does not provide additional information that 'top' provides (e.g. Cpu%, thread count etc):
((ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE);
After doing a lot of homework I got this working! Following way 'top' can be used with as many options:
String[] cmd = {"sh","-c",
"top -m 100 -n 1"
};
Process proc = Runtime.getRuntime().exec(cmd);
I have use -m and -n options and its working great. See manual for whole list of options:
'top' options
I am using
Process psProc = Runtime.getRuntime().exec("top -n 1 -d 5");
to get all the process running and then calculate CPU usage for android apps.
Related
I'm doing a simple app that show the currently process in android, like a shell.
My app execute ls, cd, makedir and other commands, but top or htop command doesnt. (htop doesn't recognize, and top, the app freeze). I need root to this? I've downloaded the terminal app in unrooted android and top command works.
my app has 2 class. a principal and a shell
principal class
public void onClick(View arg0) {
// TODO Auto-generated method stub
ShellExecuter exe = new ShellExecuter();
command = input.getText().toString();
String outp = exe.Executer(command);
out.setText(outp);
Log.d("Output", outp);
}
shell class
public String Executer(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
String response = output.toString();
return response;
}
Why some commands the app works and top for example doesn't??
If you have your Device connected, go to the shell to see what commands you have available using the following command in your computer's command line:
adb shell
At first glance you will be able to tell that "top" is a job that "displays and update sorted information about processes" and it blocks the shell commands line, hence, in your application is locking the thread that executed that command.
Hope it Helps!
Regards!
thanks. adb shell with top command show the process
but
p = Runtime.getRuntime().exec("top");
doesn't maybe works??
I don't understante cause my app freeze
or a top -n 1 not fixed?
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);
I want to display application logs.
On terminal I used this command: adb logcat -s brief *:V|grep "pid"
It's display My Application logs.
pid means application pid which is display in logcat table.
public static String logProc()
{
String value = "";
try
{
String cmd[] = {"logcat","-s","brief","*:V","|","grep",
android.os.Process.myPid()+""};
Process p = Runtime.getRuntime().exec(cmd,null, null);
BufferedReader reader = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null)
{
value += line + "\n";
line = reader.readLine();
}
p.waitFor();
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
Most official Android builds do not come with grep (Edit: more recent releases now do)
You can install busybox if you want extra commands - without root you would have to put it in an alternate location.
You have the additional problem that you are trying to exec() a shell command to connect two programs via pipes, which isn't going to work unless you exec a shell interpreter and give it that command. Or you could set up the pipe yourself and exec both programs.
But since you are writing a program, it would probably be simpler to do your pattern matching in the java code.
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.
I read the other posts and can't figure out the "trick".
I looked at Log Collector but can't use a separate APK. I'm basically using the same approach and I consistently get nothing back on the processes inputstream.
I have READ_LOGS in the manifest.
From within my default activity, I'm able to get the log, but if I move the logic to another activity or utilize an asynctask, no output is returned.
this code is from my default activity... inline, i dump it to the log
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
Log.d(LOGTAG, "Logcat: " +log.toString());
} catch (IOException e) {}
if i wrap it in an asynctask or just inline it in another activity, it returns nothing
ArrayList<String> commandLine = new ArrayList<String>();
//terminate on completion and suppress everything except the filter
commandLine.add("logcat -d -s");
...
//replace asynctask with inline (could not get log in asynctask)
showProgressDialog(getString(R.string.acquiring_log_progress_dialog_message));
final StringBuilder log = new StringBuilder();
BufferedReader bufferedReader = null;
try{
Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null){
log.append(line);
log.append(MangoApp.LINE_SEPARATOR);
}
sendIntent.putExtra(Intent.EXTRA_TEXT, log.toString());
startActivity(Intent.createChooser(sendIntent, getString(R.string.chooser_title)));
dismissProgressDialog();
dismissMainDialog();
finish();
}
catch (IOException e){
dismissProgressDialog();
showErrorDialog(getString(R.string.failed_to_get_log_message));
Log.e(LOGTAG, "Log collection failed: ", e);//$NON-NLS-1$
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ignore) {}
}
}
Can anyone spot the diff or explain the magic? I'm pretty sure the commandline is right in the second version so scratching my head. I'm using 2.1 SDK 7 on the emulator.
Thanks
Hope this will be helpful, you don't have to create file by your self just execute the below command, to get the error info.
Runtime.getRuntime().exec("logcat -v time -r 100 -f /sdcard/log.txt *:E");
Logcat parameters options:
-r <size in kilobytes> -> for specifying the size of file
-f <filename> -> file to which you want to write the logs.
Can you try it without the ArrayList. Just pass the command String
I have implemented it in the following way (without the ArrayList). It works for me.
String baseCommand = "logcat -v time";
baseCommand += " MyApp:I "; // Info for my app
baseCommand += " *:S "; // Silence others
ServicesController.logReaderProcess = Runtime.getRuntime().exec(baseCommand);