UPDATE: first solution only executes a list of commands in a file in /res/raw/
. It's not a real solution.
Look at second part for a complete solution.
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("my_file_name_without_extension", "raw", getPackageName()));
BufferedReader r = new BufferedReader(new InputStreamReader(ins));
StringBuilder total = new StringBuilder();
String line;
try {
while((line = r.readLine()) != null) {
total.append(line);
total.append(" ; ");
}
total.delete(total.length() - 3, total.length() -1); // Remove delimiter (;) at end
r.close();
ins.close();
} catch(IOException e) {}
try {
Process proc = Runtime.getRuntime()
.exec(new String[] {"sh", "-c", total.toString()});
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
Log.v("TAG", "exec failed");
}
I tested the above code with a script file containing only the lines
cp /mnt/sdcard/Folder1/file /mnt/sdcard/Folder2/
cp /mnt/sdcard/Folder1/file1 /mnt/sdcard/Folder2/
in res/raw
.
You'll have to remove the shebang and any empty line from your script. Also, I believe you'll have to include each command in a single line, i.e. you can't have a command spread over multiple lines. Or you could just edit the string building part to suit your particular case.
COMPLETE SOLUTION WITH ROOT ACCESS
InputStream is = getResources().openRawResource(getResources().getIdentifier("script_name_without_extension", "raw", getPackageName()));
boolean copysuccess = false;
// Copy from /res/raw/script.sh to /data/data/com.mycompany.myapp/files/script.sh
// because we need to chmod the script
File file = new File(getFilesDir(), "script.sh");
String scriptPath = file.getAbsolutePath();
if(!file.exists()) {
try {
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4*1024];
int read;
while((read = is.read(buffer))!=-1){
output.write(buffer,0, read);
}
copysuccess = true;
output.flush();
output.close();
is.close();
} catch(Exception e) {
copysuccess = false;
// TODO perform cleanup
}
// perform chmod now
if(copysuccess) {
try {
Process proc = Runtime.getRuntime()
.exec(new String[] {"su", "-c", "chmod 755 "+ scriptPath});
proc.waitFor();
} catch (Exception e) {
}
}
}
// Execute the script now
try {
Process proc = Runtime.getRuntime()
.exec(new String[] {scriptPath});
proc.waitFor();
} catch (Exception e) {
}