[HowTo]Execute Root Commands and read output - Java for Android App Development

You can learn here how to execute shell commands as root and read output and errors
What you will need:
Eclipse with ADT plugin
Basic knowledge of java
Rooted android device
Note
Root commands should always be executed in background thread, you can use AsyncTask for example
I won't explain here how to use AsyncTask, maybe in another tut.
Also note that I'm a relative beginner myself so I won't use professional terms I'll try to explain in my own words, so I'm sorry in advance if you have no idea what I'm talking about
1. First thing that we need to do is open a new root shell like this:
Code:
Process process = Runtime.getRuntime().exec("su");
Make sure to destroy this process after finished
2. Open input output and error streams to write commands and read output
Code:
OutputStream stdin = process.getOutputStream();
stdin is used to write commands to shell. This is OutputStream, which means that using this stream we can execute command(like writing command in terminal)
Code:
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();
stderr and stdout are used to read output and error of a command which we executed.
3. Now we actually execute commands
Code:
stdin.write(("ls\n").getBytes());
//after you exec everything that you want exit shell
stdin.write("exit\n".getBytes());
"\n" at the end of the command means new line(like when you press enter in terminal). This is important, if you dont add new line it same like you didn't press enter
4. Flush and close OutputStream
Code:
stdin.flush(); //flush stream
stdin.close(); //close stream
5. Read output and error of a executed command
Code:
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while ((line = br.readLine()) != null) {
Log.d("[Output]", line);
}
br.close();
br =
new BufferedReader(new InputStreamReader(stderr));
while ((line = br.readLine()) != null) {
Log.e("[Error]", line);
}
br.close();
We read output and error (if any) line by line and write it to logcat
You can of course do anything with output(display in TextView for example)
6. Finally we destroy opened shell
Code:
process.waitFor();//wait for process to finish
process.destroy();
You need to handle InteruptedException and IOException.
Hope this helps someone. Again sorry for stupid explanations. I totally understand all this but English isn't my primary language so its a but hard to explain...
Here is whole code;
Code:
try {
String line;
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();
stdin.write(("ls\n").getBytes());
stdin.write("exit\n".getBytes());
stdin.flush();
stdin.close();
BufferedReader br =
new BufferedReader(new InputStreamReader(stdout));
while ((line = br.readLine()) != null) {
Log.d("[Output]", line);
}
br.close();
br =
new BufferedReader(new InputStreamReader(stderr));
while ((line = br.readLine()) != null) {
Log.e("[Error]", line);
}
br.close();
process.waitFor();
process.destroy();
} catch (Exception ex) {
}

Yea roottools is better solution, it handles opening shell for you, its easier, less code, and in my experience a little bit faster.
Here is an example:
Code:
Command command = new Command(0, "ls")
{
@Override
public void output(int id, String line)
{
// Handle output here
}
};
RootTools.getShell(true).add(command).waitForFinish();
And also do this when exiting application
Code:
RootTools.closeAllShells();
Sent from my Evo 3D GSM using Tapatalk 2

Everyone should read the How-To SU guide by Chainfire:
http://su.chainfire.eu/
Usable example code is on Github. In the meanwhile there's an interactive shell (like in RootTools) available too:
https://github.com/Chainfire/libsuperuser

I noticed that you called your InputStream stdout and your OutputStream stdin. Is there any reason that you chose to reverse the usual naming?

Great work but i would be delighted if op mentioned root commands and how to use them

octobclrnts said:
I noticed that you called your InputStream stdout and your OutputStream stdin. Is there any reason that you chose to reverse the usual naming?
Click to expand...
Click to collapse
Its confusing I know.
I'll try to explain
You use InputStream to read output of the shell so I called it stdout
Output of a shell/terminal is called stdout
You use OutputStream to write to shell(input to shell) so its stdin
Passing commands to terminal is stdin
It stands for standard output/input
More about stdin, stdout, stderr
http://en.m.wikipedia.org/wiki/Standard_streams
Sent from my Evo 3D GSM using Tapatalk 2

sak-venom1997 said:
Great work but i would be delighted if op mentioned root commands and how to use them
Click to expand...
Click to collapse
There is no such thing as root command.
commands can be executed as root user or as normal user.
Sent from my Evo 3D GSM using Tapatalk 2

pedja1 said:
There is no such thing as root command.
commands can be executed as root user or as normal user.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
You didn't get me sir I ment the commands which run as root and how can developers utilize them
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!

sak-venom1997 said:
You didn't get me sir I ment the commands which run as root and how can developers utilize them
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
Click to expand...
Click to collapse
I'm not really sure what you are asking. Any command can be executed as root.
Maybe you should read a bit about linux and shell
Sent from my Evo 3D GSM using Tapatalk 2

pedja1 said:
I'm not really sure what you are asking. Any command can be executed as root.
Maybe you should read a bit about linux and shell
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
No I was talking about the commands which require root to run like ifconfig
Sry for trouble I have no linux knowledge
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!

sak-venom1997 said:
No I was talking about the commands which require root to run like ifconfig
Sry for trouble I have no linux knowledge
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
Click to expand...
Click to collapse
There are some commands that will just make sense as root. However, why should anyone write a tutorial about how to use some commands very few persons will need. Google "Linux command <what you want to do>" and you will find explanations. Many commands are just more flexible when executed like this.
I really recommend that. You will need it when you develop a root app. And you can use the adb shell! Great help.
@OP: What's about mentioning that you should use the busybox commands as the system's implementation of the shell commands differs from device to device and from ROM to ROM?
I also recommend RootTools. One of the best libraries in my opinion!

nikwen said:
.
@OP: What's about mentioning that you should use the busybox commands as the system's implementation of the shell commands differs from device to device and from ROM to ROM?
I also recommend RootTools. One of the best libraries in my opinion!
Click to expand...
Click to collapse
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2

pedja1 said:
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Click to expand...
Click to collapse
You are right. It is true that nobody would use busybox for very simple commands.
However, RootTools has the RootTools.offerBusyBox(Activity activity) Method which opens Google Play to download a busybox installer.
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
I understood what you wanted to do.
Great job, btw. Would have been glad if I had had this when I started with root apps.

Great Work!!!
I found how to execute root commands before. But this post has the best explanation. Thanks a lot!

pedja1 said:
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
I once did run into troubles parsing the results of "ls" command. Usually 'ls' is just the short table-style list, while you could get all the details with 'ls -l'. This is what I needed. But when testing on the Motorola Milestone unfortunately 'ls' was sym-linked to 'ls -l', therefore calling 'ls -l' would result in an error message. Don't know if more devices act like that (didn't test on any other Motorola phones, and the Milestone is quite old by now), but maybe it still makes sense to use busybox for 'normal' command in some cases...

Hello,
I am trying to run a script kept in my assests folder of my app. It is Root.sh which contains -
Code:
su
cd system
mkdir abcdjdj
This is my java code:-
Code:
String path = "file:///android_asset/Root.sh";
Process p = new ProcessBuilder().command(path).start();
But now I get a runtime error -
Code:
04-22 15:08:03.144: E/AndroidRuntime(785): Caused by: java.io.IOException: Error running exec(). Command: [file:///android_asset/Root.sh] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, ANDROID_STORAGE=/storage, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/mnt/sdcard, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/mms-common.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,32768]
Can anyone please help me?
Thanks.

abcdjdj said:
Hello,
I am trying to run a script kept in my assests folder of my app. It is Root.sh which contains -
Code:
su
cd system
mkdir abcdjdj
This is my java code:-
Code:
String path = "file:///android_asset/Root.sh";
Process p = new ProcessBuilder().command(path).start();
But now I get a runtime error -
Code:
04-22 15:08:03.144: E/AndroidRuntime(785): Caused by: java.io.IOException: Error running exec(). Command: [file:///android_asset/Root.sh] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, ANDROID_STORAGE=/storage, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/mnt/sdcard, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/mms-common.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,32768]
Can anyone please help me?
Thanks.
Click to expand...
Click to collapse
Why don't you do it this way?
Code:
Runtime.getRuntime().exec("su", "-c", "cd system; mkdir abcdjdj");
Note that you need to pass the commands you want to execute to the command method, not the path.

nikwen said:
Why don't you do it this way?
Code:
Runtime.getRuntime().exec("su", "-c", "cd system; mkdir abcdjdj");
Note that you need to pass the commands you want to execute to the command method, not the path.
Click to expand...
Click to collapse
It gives a syntax error. I guess it should have been - Runtime.getRuntime().exec(new String[] { "su", "-c", "cd system; mkdir abcdjdj" });
It runs fine on my phone but I still don't see a folder called abcdjdj is /system

abcdjdj said:
It gives a syntax error. I guess it should have been - Runtime.getRuntime().exec(new String[] { "su", "-c", "cd system; mkdir abcdjdj" });
It runs fine on my phone but I still don't see a folder called abcdjdj is /system
Click to expand...
Click to collapse
You are right, it should have been that.
Try to add the full path:
Code:
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(new String[] {"su", "-c", "mkdir /system/abcdef"});
runtime.exec(new String[] {"su", "-c", "mkdir /system/aaab; mkdir /system/aaac"});
} catch (IOException e) {
e.printStackTrace();
}
I think that executing your first idea should work if you execute
Code:
runtime.exec("su");
and then write the commands to the outputstream as described in the first post of this thread.
---------- Post added at 06:13 PM ---------- Previous post was at 06:06 PM ----------
However, I recommend using roottools.
If you need to execute commands rarely it will be fine that way, but if you need to execute commands often, there will be annoying Toast messages every time. Using roottools, there will be such a message just once when the app requests SU rigths for the first time after the launch.

Ichigo said:
Yes, root tools is a great alternative. I use it a lot in my app. If you want, check my github for examples.
Click to expand...
Click to collapse
For a very basic tutorial, check this: http://code.google.com/p/roottools/wiki/Usage

Related

[Q] Reboot, Su, App

Hi, i am trying to run adb and su commands in onclicklistener of my button of android app and here is my code
Code:
btnCheckSu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Process p; String[] st = new String[3];
try {
st[0]="/system/bin/su";
st[1]="-c";
st[2]="reboot";
p = Runtime.getRuntime().exec(st);
Toast.makeText(SUCheck.this, "Rebooting...", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I do get the prompt for su but then phone does not reboot...any help please
thanks
Well im not sure about the su commands but the reboot intent is restricted to processes signed with the same key as the platform you are using (essentially the key used to sign the rom you are using)
It could be the same with using su to reboot. Not sure though
--------
I tried it on the terminal emulator and it worked after entering the command twice for some reason
From something awesome
Try your commands via adb root shell first. If they work then u know the condemns are good and can try something else. All so without capturing process output there it's no way to know what's going on.
Sent from my MB860 using Tapatalk
Why not use the standard android api?
Code:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot("");
You'll need the REBOOT permission though.
HomerSp said:
Why not use the standard android api?
Code:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot("");
You'll need the REBOOT permission though.
Click to expand...
Click to collapse
Because as i said before the reboot permission is only valid on system apps signed with the platform key
From something awesome
killersnowman said:
Because as i said before the reboot permission is only valid on system apps signed with the platform key
From something awesome
Click to expand...
Click to collapse
You're right, sorry.
Try this instead, it worked fine for me.
Code:
Runtime.getRuntime().exec("su -c /system/bin/reboot");
i guys
thanks for the above replies...
but none of the above suggestion has worked for me...any other clues please
thanks
.../me repeats himself...
CAPTURE UR OUTPUT, without it we cant know what is going wrong.
Try your commands via adb shell first, if they work there they will also work via your phone.
yup, great.... adb working through my pc shell
capturing output...i have to work that out how...cheers
hisheeraz said:
yup, great.... adb working through my pc shell
capturing output...i have to work that out how...cheers
Click to expand...
Click to collapse
from your process create datastreams for your process.getInputStream() and process.getErrorStream(). After execution dump streams to file/logcat/w/e.
hisheeraz said:
yup, great.... adb working through my pc shell
capturing output...i have to work that out how...cheers
Click to expand...
Click to collapse
Try this:
Code:
btnCheckSu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Process p; String[] st = new String[3];
try {
st[0]="/system/bin/su";
st[1]="-c";
st[2]="reboot";
p = Runtime.getRuntime().exec(st);
[COLOR="Red"] String s;
DataInputStream is=new DataInputStream(p.getInputStream());
DataInputStream er=new DataInputStream(p.getErrorStream());
Log.i("MyApp","stdout:\n");
while((s=is.readLine())!=null){
Log.i("MyApp",s+"\n");
}
Log.i("MyApp","stderr:\n");
while((s=er.readLine())!=null){
Log.i("MyApp",s+"\n");
}
[/COLOR]
Toast.makeText(SUCheck.this, "Rebooting...", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sorry for being such a pain but my Log.i is empty there is absolutely nothing there
even after reinstalling the app in my phone nothing is in Log.i
help please...
EDIT:1
HERE IS THE LOG.I
sdtout:
stderr:
not permitted!
also i am using REBOOT permission in my manifest...i donot think i need it but just in case
hisheeraz said:
sorry for being such a pain but my Log.i is empty there is absolutely nothing there
even after reinstalling the app in my phone nothing is in Log.i
help please...
EDIT:1
HERE IS THE LOG.I
sdtout:
stderr:
not permitted!
Click to expand...
Click to collapse
bla,
try without -c. then also try...
reboot
reboot -f
busybox reboot
busybox reboot -f
hey thanks
/system/bin/su
-c
busybox reboot -f
is working...but
busybox reboot recovery -f
of
busybox reboot recovery
is not working. thanks for your effort and help,
i will dig into this tomorrow and will post you my feed back, it is really late here in AU :O
regards

[Q][DEV] Writing to /data partition without root?

Hello I am desperately trying to run a shell script from my java app.
I tried to use http://developer.android.com/reference/java/lang/Runtime.html#exec%28java.lang.String%29 Runtime Exec to run it and it works except nothing really happens and the script is not executed.
My command was "/system/bin/sh /data/local/test.sh", of course properly chmodded. I tried running the test.sh directly, even tried opening a SH instance and pushing commands to the console via output buffer - nothing works.
When I try to run SU for example using any of these methods, I get prompted for superuser access, so it does work, just doesn't work like I want.
Anybody has any idea what's wrong? Or alternative way to run a script post-boot? (init.d executes too early in the startup process for my needs)
Are you capturing the error stream, or just the output stream?
This is everything I tried:
Code:
String[] str = { "/system/bin/sh", "/data/local/test.sh" };
Process p = Runtime.getRuntime().exec(str);
p.waitFor();
Code:
Process p2 = Runtime.getRuntime().exec("/system/bin/sh /data/local/test.sh");
p2.waitFor();
Code:
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("/system/bin/sh");
OutputStream os = p.getOutputStream();
String str = "/data/local/test.sh";
byte[] cmds = str.getBytes();
os.write(cmds);
os.flush();
os.close();
calling just "/system/bin/sh" or "su" works - it actually waits indefinitely in each approach but once I try to execute a script it won't budge. I also attempted to run other parametrized commands like "setprop persist.sys.use_dithering 0" and it also failed. I'll try to intercept the error stream, good point.
nik3r said:
This is everything I tried:
Code:
String[] str = { "/system/bin/sh", "/data/local/test.sh" };
Process p = Runtime.getRuntime().exec(str);
p.waitFor();
Click to expand...
Click to collapse
You need the "-c" option to execute a script:
Sorry I missed that in your first post.
Code:
String[] str = { "/system/bin/sh", [COLOR="Red"]"-c",[/COLOR] "/data/local/test.sh" };
Process p = Runtime.getRuntime().exec(str);
p.waitFor();
nope, this is what I have
Code:
String[] str = { "/system/bin/sh", "-c", "/data/local/test.sh" };
Process p = Runtime.getRuntime().exec(str);
p.waitFor();
still no effect, the /data/local/test.sh is 0777 and only contains
Code:
echo "success" > /data/local/testresult.txt
The same command works from ADB even without the -c switch but with the exec command nothing happens.
finally progress
Update: according to the error output the file gets executed BUT it doesn't have permission to write in /data/local/ same problem if I try to write to this dir with java API.
My script needs to write there so I have only one question - is there a permission that would allow me to execute a script with access right to /data partition without root?
I want to modify the userdata partition after first boot of the ROM but I can't ask the user for root, I want to execute my tweaks and reboot the device before even the android login wizard appears so asking for root that has a prompt with timeout is not an option.
I know of an alternative way to do it but it's even more hacky than this and I would like to avoid someone vomiting over my code
Does it need to be /data/local? /data/local/tmp is world-writable on most devices.
In the end it needs to be /data/data/ actually, I want to mess with default settings of apps, system settings database for example... does that mean I need root or game over? Is there no permission for app to get access to the userdata partition?
As far as I know, the Dalvik system was set up that way on purpose to prevent errant apps from causing any problems elsewhere, and to maintain decent security (look how out of control Windows has become), so to answer your question, Yes, I believe you will need root.
nik3r said:
In the end it needs to be /data/data/ actually, I want to mess with default settings of apps, system settings database for example... does that mean I need root or game over? Is there no permission for app to get access to the userdata partition?
Click to expand...
Click to collapse
No, you can't write to /data/data without root (as that would be a major security risk).
Ok thanks guys I will try my dirty workaround

{Q}Restart a system process

Hi
I'm developing a new app that make changes into SystemUi.apk and i don't want restart me device to see changes and I want just restart SystemUi.apk...
is there any way???
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
plz take look at this...
http://forum.xda-developers.com/showthread.php?t=2434597
poria1999 said:
Hi
I'm developing a new app that make changes into SystemUi.apk and i don't want restart me device to see changes and I want just restart SystemUi.apk...
is there any way???
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
plz take look at this...
http://forum.xda-developers.com/showthread.php?t=2434597
Click to expand...
Click to collapse
You can restart the service using adb's ActivityManager (am) using the following command
Code:
am startservice -n com.android.systemui/.SystemUIService
To execute the same command from your app, make use of Runtime.
Code:
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su -c am startservice -n com.android.systemui/.SystemUIService");
}
catch (IOException e) {
e.printStackTrace();
}
vijai2011 said:
You can restart the service using adb's ActivityManager (am) using the following command
Code:
am startservice -n com.android.systemui/.SystemUIService
To execute the same command from your app, make use of Runtime.
Code:
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su -c am startservice -n com.android.systemui/.SystemUIService");
}
catch (IOException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
tnx
I have one question more...
can u give me a example code to mount system and write sth on?
Edit:How i can start it again?
poria1999 said:
tnx
I have one question more...
can u give me a example code to mount system and write sth on?
Click to expand...
Click to collapse
Try below code. Cant test it ATM
Code:
runtime.exec("su -c mount -o remount,rw /system");
File myfile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
myfile.createNewFile();
String data ="My test data";
//write the data in file
if(myfile.exists())
{
try {
OutputStream os = new FileOutputStream(myfile);
os.write(data);
os.close();
Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show();
}catch (IOException e)
{e.printStackTrace();}
runtime.exec("su -c" + Environment.getExternalStorageDirectory() + File.separator + "test.txt" + "/system/");
}
//deleting the temp file
file.delete();
Toast.makeText(this, "File copied and deleted from temp dir", Toast.LENGTH_SHORT).show();
To start it again, put that in a function and call that function whenever you want to execute it.
Example of function:
Code:
public void myfunc(){
//Your code to be executed more than once
}
And in some other function, say onCreate(), call
Code:
myfunc();
vijai2011 said:
You can restart the service using adb's ActivityManager (am) using the following command
Code:
am startservice -n com.android.systemui/.SystemUIService
To execute the same command from your app, make use of Runtime.
Code:
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su -c am startservice -n com.android.systemui/.SystemUIService");
}
catch (IOException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
this code doesn't work for me bro...
Edit:
vijai2011 said:
Try below code. Cant test it ATM
Code:
runtime.exec("su -c mount -o remount,rw /system");
File myfile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
myfile.createNewFile();
String data ="My test data";
//write the data in file
if(myfile.exists())
{
try {
OutputStream os = new FileOutputStream(myfile);
os.write(data);
os.close();
Toast.makeText(this, "File created successfully", Toast.LENGTH_SHORT).show();
}catch (IOException e)
{e.printStackTrace();}
runtime.exec("su -c" + Environment.getExternalStorageDirectory() + File.separator + "test.txt" + "/system/");
}
//deleting the temp file
file.delete();
Toast.makeText(this, "File copied and deleted from temp dir", Toast.LENGTH_SHORT).show();
To start it again, put that in a function and call that function whenever you want to execute it.
Example of function:
Code:
public void myfunc(){
//Your code to be executed more than once
}
And in some other function, say onCreate(), call
Code:
myfunc();
Click to expand...
Click to collapse
if i want replace sth from into an apk to system dir what i suppose to do?
poria1999 said:
this code doesn't work for me bro...
Edit:
if i want replace sth from into an apk to system dir what i suppose to do?
Click to expand...
Click to collapse
That's gonna be different. You have to put the file in asserts and extract the file to system more or less the same why like creating the file and copying it to system.
And for systemUI restart, you can try this:
Code:
Process p;
p = Runtime.getRuntime().exec("sh");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("am startservice -n com.android.systemui/.SystemUIService\n");
Its pretty much the same but with a little different approach.
vijai2011 said:
That's gonna be different. You have to put the file in asserts and extract the file to system more or less the same why like creating the file and copying it to system.
And for systemUI restart, you can try this:
Code:
Process p;
p = Runtime.getRuntime().exec("sh");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("am startservice -n com.android.systemui/.SystemUIService\n");
Its pretty much the same but with a little different approach.
Click to expand...
Click to collapse
Bro codes don't work for me!!!
I tried all of codes that u gave me but they just make an app than ask me for root permission and don't do any thing...
Sent from my LT18i using Tapatalk 2
poria1999 said:
Bro codes don't work for me!!!
I tried all of codes that u gave me but they just make an app than ask me for root permission and don't do any thing...
Sent from my LT18i using Tapatalk 2
Click to expand...
Click to collapse
Let me try a working code today. Sorry for posting non working codes as I can not home yestersay to test 'em. BTW, you can also look for it in opensource xposed framework modules because many xposed modules needs to do a restart of systemui.
Sent from my GT-N7000 using xda app-developers app
Ok...a friend of mine who has more experience than me said, the code is correct but is not working with recent builds. Searching doesnt give me any convincing results. So thought to provide you code to hot reboot. This code is tested and works well.
Code:
try {
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "setprop ctl.restart zygote"});
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
This will cause the zygote to restart which will in turn makes the whole system core reboot. Works well on my Galaxy note running 4.1.2. This the easiest method I can think although I could restart systemui by killing SystemUI process by "kill pid" But it would be lots of work to find systemui pid because it is not static
vijai2011 said:
Let me try a working code today. Sorry for posting non working codes as I can not home yestersay to test 'em. BTW, you can also look for it in opensource xposed framework modules because many xposed modules needs to do a restart of systemui.
Sent from my GT-N7000 using xda app-developers app
Click to expand...
Click to collapse
Tnx bro,that is no problem...
Do u know how to use xposed framework?
Sent from my LT18i using Tapatalk 2
vijai2011 said:
Ok...a friend of mine who has more experience than me said, the code is correct but is not working with recent builds. Searching doesnt give me any convincing results. So thought to provide you code to hot reboot. This code is tested and works well.
Code:
try {
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "setprop ctl.restart zygote"});
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
This will cause the zygote to restart which will in turn makes the whole system core reboot. Works well on my Galaxy note running 4.1.2. This the easiest method I can think although I could restart systemui by killing SystemUI process by "kill pid" But it would be lots of work to find systemui pid because it is not static
Click to expand...
Click to collapse
But I don't want reboot whole device
Where I can find system ui pid and how I use from?
Tnx
Sent from my LT18i using Tapatalk 2
poria1999 said:
Tnx bro,that is no problem...
Do u know how to use xposed framework?
Sent from my LT18i using Tapatalk 2
Click to expand...
Click to collapse
You need to use xposed framework for?
poria1999 said:
But I don't want reboot whole device
Where I can find system ui pid and how I use from?
Tnx
Sent from my LT18i using Tapatalk 2
Click to expand...
Click to collapse
That's not a whole system reboot. It only restarts core system services. So its already fast than normal reboot.
Anyway, NVM, found a better working method which is working on my Galaxy Note N7000 running 4.1.2
Code:
try {
Process proc = Runtime.getRuntime()
.exec("su -c pkill com.android.systemui ");
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
vijai2011 said:
You need to use xposed framework for?
That's not a whole system reboot. It only restarts core system services. So its already fast than normal reboot.
Anyway, NVM, found a better working method which is working on my Galaxy Note N7000 running 4.1.2
Code:
try {
Process proc = Runtime.getRuntime()
.exec("su -c pkill com.android.systemui ");
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
Click to expand...
Click to collapse
woks great!!!
so now how I can start it(SystemUI) again?
and one question more...
how i can change wallpaper?
EDIT:How i can check a process is running or not?
poria1999 said:
woks great!!!
so now how I can start it(SystemUI) again?
and one question more...
how i can change wallpaper?
EDIT:How i can check a process is running or not?
Click to expand...
Click to collapse
That would automatically restart the SystemUI. for wallpaper try this. Will help u a lot.

Scripting Commands in Android App?

Hi All,
Things I am trying to do:
1. Connect to remote system
2. Run perl command and get the output on screen.
Could you please guide me on the process where in I can connect to a remote windows/unix machine and run build commands.
Any examples?
Thanks for your help.
Thanks,
Kino
Hi!
I've made something similar - An App that runs some shell scripts on an Ubuntu server over SSH.
Here are some code snippets, hope this helps you
Code:
JSch jsch = new JSch();
Session session = jsch.getSession([I]'ssh-username'[/I],IP, [I]'ssh-port'[/I]);
session.setPassword(SW); // SW ... password ssh-user (for me it's the same pw, ssh-user = su)
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
Channel channel = session.openChannel("exec");
Code:
if(SU) // If Command should run as SU
{
sudoCommand = "sudo -S -p '' " + command;
}
else
{
sudoCommand = command;
}
((ChannelExec) channel).setCommand(sudoCommand);
((ChannelExec) channel).setPty(true);
channel.connect();
OutputStream out = channel.getOutputStream();
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOutputStream(responseStream);
if(SU)
{
out.write((SW + "\n").getBytes());
out.flush();
}
Thread.sleep(1000);
out.write(("logout" + "\n").getBytes());
out.flush();
Thread.sleep(500);
out.write(("exit" + "\n").getBytes());
out.flush();
out.close();
session.disconnect();
channel.disconnect();
Thank you LinuxForce. Thats helpful. I am trying to work on this.
LinuxForce said:
Hi!
I've made something similar - An App that runs some shell scripts on an Ubuntu server over SSH.
Here are some code snippets, hope this helps you
Click to expand...
Click to collapse

Fast Keyevent Simulation (Android Shell)

I am developing a Keyboard Bot (Automated Text Typing) in which the only problem I'm facing is speed (Regardless of which device is used). The App requires root and it works perfectly fine in typing text.
Using
Code:
adb shell input text <String>
or
Code:
adb shell input keyevent <KEYCODE_NAME>
works perfectly fine in sending text to the android device, but my issue is speed.
Using something like
Code:
input keyevent KEYCODE_A KEYCODE_A KEYCODE_SPACE KEYCODE_A KEYCODE_ENTER;
will type the text quickly, but separating it into 2 commands will result in a (1 sec) delay between the 2 commands (Much Slower).
Sample Shell Code:
Method 1 (Much faster):
Code:
input keyevent KEYCODE_A KEYCODE_A KEYCODE_ENTER KEYCODE_A KEYCODE_A KEYCODE_ENTER;
Method 2:
Code:
input keyevent KEYCODE_A KEYCODE_A KEYCODE_ENTER;
input keyevent KEYCODE_A KEYCODE_A KEYCODE_ENTER;
I wanted to type a large text as fast as possible, so i called a long shell
Code:
input keyevent KEYCODE_A .... KEYCODE_ENTER
But having a shell script with input keyevent followed by a large combination of KEYCODE_A for instance, will not be executed. (Large Shell Commands are aborted)
After the shell command
Code:
input keyevent KEYCODE_A
, there will be a 1 second delay before the next "input" command executes.
What would be the best way to send large text without having long delays?
I am aware that sendevent is faster in sending large text, but how can i programmatically use it with an APP with root privilages?
Is there a way i can use Instrumentation from my root app on third party apps without having to transform my app into a system app?
Note:
The weakness of input text <String> is that it also has a limit to it's size and it can't perform special keyevents inside of it (Like the Back Button or Enter/New Line ).
I have been looking for an answer for quite sometime, but i haven't found a working method. (I searched for a way to send text using "sendevent" code.
My Sample Code: (Simple Program that will type a certain text multiple times)
Service Class
Code:
public class InputTextService extends IntentService {
public InputTextService() {
super("ServiceQAZ");
}
@Override
protected void onHandleIntent(Intent intent) {
//Using chainfire libsuperuser
Log.i("Service","Entered");
try {
Thread.sleep(5L* 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Service","Sleep Finished");
//String[] cmds = { "input text hello","input keyevent KEYCODE_ENTER"};
String[] cmds = { "input keyevent KEYCODE_H KEYCODE_E KEYCODE_L KEYCODE_L KEYCODE_O","input keyevent KEYCODE_ENTER"};
// if(Shell.SU.available()) {
for(int i = 0; i < 100; i++) {
Shell.SU.run(cmds); // Works Everywhere
//Shell.SH.run(cmds); //Only works in application
}
// }
Log.i("Service","Input Sent");
}
}
Thanks in Advance.
Hi this might be a bit off topic but I am working on my own app and the first command that the app tries to run when i press a button is mount -o rw,remount /system to get mount partition as rw, so i can further execute other commands, however app works fine on other phones but on my phone it shows the following issue in su logs :device or resource busy , can't mount , please help I've tried almost everything, i am able to mount using terminal emulator but not via app
dewankpant said:
Hi this might be a bit off topic but I am working on my own app and the first command that the app tries to run when i press a button is mount -o rw,remount /system to get mount partition as rw, so i can further execute other commands, however app works fine on other phones but on my phone it shows the following issue in su logs :device or resource busy , can't mount , please help I've tried almost everything, i am able to mount using terminal emulator but not via app
Click to expand...
Click to collapse
I would recommend that you use the library "Root Tools" which has a mount command that will try different methods of mounting a directory. I've been using it for a while and it's great.
Stround said:
I would recommend that you use the library "Root Tools" which has a mount command that will try different methods of mounting a directory. I've been using it for a while and it's great.
Click to expand...
Click to collapse
Actually my problem is something different, i am using this command in my own app and when i see the log of my app in su i see it shows that device or resource is busy, how can i overcome that
I think that my question is different from the purpose of this thread, but I do not want to build a new thread, so please forgive me.
As you know, input keyevent is a very slow command. But I tested this instead of "input keyevent 3".
"am start -c android.intent.category.HOME -a android.intent.action.MAIN"
I found out this was way faster than input keyevent 3.
So someone smart developers, could you write down the strings like "am start blah blah blah" as "input keyevent 4" (back) for me?

Categories

Resources