2

I am New to Android Programming, i need to creat an Android application to Run Shell Script on button Click Event. i am using below command but no action is happening.

 Process p;
                 try {
                     p = new ProcessBuilder()
                     .command("/data/test.sh")
                     .start();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } finally {
                     if(p!=null) p.destroy();
                 }
  1. I have created "data" folder and kept my shell script there.
  2. Having phone root permission.

Thanks in advance. :)

anupam.unique
  • 81
  • 2
  • 13

1 Answers1

1

To execute a shell script you first need to give it execution permission by using chmod +x.
Then, you can use p.waitFor() (after start()) and wait for it to finish execution.

To read the output of your script, you can do the following:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
// reading part comes here

If you are running this in an emulator, you need to look at this:
http://russelldavis.blogspot.in/2011/01/rooting-android-emulator.html

Sources:
execute shell command from android
How to Executing Shell commands through android app?

Aside:
Difference between ProcessBuilder and Runtime.exec()

Community
  • 1
  • 1
An SO User
  • 24,612
  • 35
  • 133
  • 221