Run script with android app
First, you will use Eclipse to create a simple Android helloworld app.And add a button in your layout. This is very priliminary practise of Android development which you can dig a lot more from http://d.android.com
please try this code in your button's onclick call back function:
Button b = (Button)findViewById(R.id.buttonPower); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Process p=null; try { p = new ProcessBuilder() .command("PathToYourScript") .start(); } catch (IOException e) { e.printStackTrace(); } finally { if(p!=null) p.destroy(); } } });
Here is how you can run shell script from your android app
try { Process process = Runtime.getRuntime().exec("sh /sdcard/test.sh"); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String listOfFiles = ""; String line; while ((line = in.readLine()) != null) { listOfFiles += line; } } catch (IOException e) { e.printStackTrace(); }
Well, now No errors (THANK YOU!) but do nothing..to try i've written a easy script that write a file.txt. See the code:
package com.mkyong.android;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast; import java.io.IOException;import com.example.toast.R;public class MainActivity extends Activity {private Button button;public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tab1); button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @SuppressLint("SdCardPath") @Override public void onClick(View arg0) { Process p=null; try { p = new ProcessBuilder() .command("/sdcard/Script/scritturafile.sh") .start(); } catch (IOException e) { e.printStackTrace(); } finally { if(p!=null) p.destroy(); } } });}}
The are no errors but when i press the button i think the shell doesn't go so don't create the file.txt