Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell commands from android program

This question has been asked here before but the solutions provided are not working..I am trying to display the contents of /data/dalvik-cache folder. I know that to do this we need to become su. I even did that but still i am unable to execute a shell command..

package org.linuxconfidg.Example2;

import android.app.Activity;
import android.widget.*;
import android.os.Bundle;
import java.io.*;
public class Example2Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String lsreturn=myFunLs();
        TextView tv=new TextView(this);
        tv.setText("Hello Sindhu !! Try to get it \n"+lsreturn);
        setContentView(tv);
    }

    public String myFunLs()
    {

        try {
            // Executes the command.
            Process process;
            process = Runtime.getRuntime().exec("/system/bin/su");
            process = Runtime.getRuntime().exec("/system/bin/ls /data/dalvik-cache > /data/local");
            pr
            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);
        }
    }

}

Can anyone please help me out in finding out how to run linux commands in android application. I am testing this app in my emulator which is defaultly rooted

like image 936
nikhil Avatar asked Sep 16 '11 19:09

nikhil


1 Answers

You can't simply run 'su' on the emulator, there's no root access by default. You'll need to install the 'su' program as well as the SuperUser.apk, and you'll have to do this each time you start the emulator unless using snapshots.

More information and links to the files you need can be found here on SO as well as this blog post by Russell Davis

like image 76
Pedantic Avatar answered Sep 28 '22 06:09

Pedantic