public String ls() {
Class<?> execClass = Class.forName("android.os.Exec");
Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
int[] pid = new int[1];
FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
String output = "";
try {
String line;
while ((line = reader.readLine()) != null) {
output += line + "\n";
}
}
catch (IOException e) {}
return output;
}
Comprobar el código mencionado aquí:
How to run terminal command in Android application?
try {
// Executes the command.
Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Referencias
this code GScript
La llamada a read() se detiene si la llamada al sistema no devuelve nada. En este caso particular, "ls" siempre debería devolver algo, pero solo tenga en cuenta que podría quedarse bloqueado con otros comandos. – pmont
@glodos ¿Hay alguna manera de hacerlo sin especificar BUFF_LEN? Es decir, ¿leer una línea a la vez hasta que no haya más líneas? –
Hola, he estado usando tu ejemplo con éxito pero estoy luchando para que esto funcione en Android Nougat. Alguien tiene alguna idea para esto? – zeroprobe