Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Runtime.getRuntime().exec("cmd")

In my application I'm trying to execute a native code which is present on my SD card.

File sdCard = getExternalFilesDir(null); // directory where native file is placed
String nativeFile = "nativeFile";

String cmd = "shell /system/bin/chmod 0777 " + sdCard.getAbsolutePath() + "/" + nativeFile;
Process proc = Runtime.getRuntime().exec(cmd);

But as soon as Runtime.getRuntime().exec(cmd) is executed, it throws error:

java.io.IOException: Error running exec(). Command: [shell, /system/bin/chmod, 0777, /storage/emulated/0/Android/data/com.example.andridutilproject/files/native] Working Directory: null Environment: null

Any suggestions, how to resolve this?

like image 998
adam black Avatar asked Oct 30 '14 21:10

adam black


People also ask

What does runtime getRuntime () exec () do?

getRuntime(). exec() method to use the command-line to run an instance of the program "tesseract". the first argument calls the tesseract program, the second is the absolute path to the image file and the last argument is the path and name of what the output file should be.

What is runtime getRuntime ()?

getRuntime() method returns the runtime object associated with the current Java application. Most of the methods of class Runtime are instance methods and must be invoked with respect to the current runtime object.

What is exec method in Java?

exec(String[] cmdarray, String[] envp) method executes the specified command and arguments in a separate process with the specified environment. This is a convenience method. An invocation of the form exec(cmdarray, envp) behaves in exactly the same way as the invocation exec(cmdarray, envp, null).


2 Answers

First, you should wrap calls to exec in a try-catch-clause to catch IOExceptions.

Second, use exec(java.lang.String[]) to execute a command with parameters. For example, similar to

Runtime.getRuntime().exec(new String[]{ "shell", "/system/bin/chmod", "0777", sdCard.getAbsolutePath() + "/" + nativeFile });
like image 90
cygery Avatar answered Oct 04 '22 16:10

cygery


The sdcard in an Android system is usually disabled for execution. Therefore even if you correctly execute the chmod command it will fail.

You can test that easily. Start the shell via USB (adb shell) and execute the chmod command. It will fail with an error message like "Bad mode".

Therefore you have to copy the file to a different location where you have write access and then set the executable bit on that copy. You can try to copy the file for example to "/data/local/tmp/" but I am not sure if that path is still usable.

like image 42
Robert Avatar answered Oct 04 '22 15:10

Robert