Call a binary executable program (native executable) in Android)

Source: Internet
Author: User

A few days ago, when I needed to call the binary program in java code, I found some information on the Internet and wrote something to record.

Android is also a linux-based system, and can also run binary executable files. However, Android only allows you to install and run the apk file in a direct way. Although NDK can use the binary code of C by means of dynamic link library, it is inconvenient after all. At least we can call some basic linux commands, such as ls and rm.

 

Method 1: Runtime.exe c (String [] args)


This method is provided by the java language and can be used in Android. Args is an array of parameters to be executed. The general usage is as follows:

 

String [] args = new String [2];

Args [0] = "ls ";

Args [1] = "-l ";

Try
{
Process process = runtime.getruntime(cmd.exe c (arg );


// Get the err line

InputStream stderr = process. getErrorStream ();
InputStreamReader isrerr = new InputStreamReader (stderr );
BufferedReader brerr = new BufferedReader (isrerr );


// Get the output line
InputStream outs = process. getInputStream ();
InputStreamReader isrout = new InputStreamReader (outs );
BufferedReader brout = new BufferedReader (isrout );


String errline = null;

String result = "";

// Get the whole error message string
While (line = brerr. readLine ())! = Null)
{
Result + = line;
Result + = "/n ";

}

If (result! = "")

{

// Put the result string on the screen

}

 

// Get the whole standard output string

While (line = brout. readLine ())! = Null)
{
Result + = line;
Result + = "/n ";
}
If (result! = "")
{

// Put the result string on the screen

}

} Catch (Throwable t)
{
T. printStackTrace ();
}

 

The above code executes the standard linux Command ls-l. The standard output after this command is executed is in brout. If an error occurs, such as a parameter error or a command error, it will be placed in brerr.

If necessary, read it from it.

 

Method 2: Class. forName ("android. OS. Exec ")

 

This method was found by a foreigner, originally posted here: http://gimite.net/en/index.php? Run % 20 native % 20 executable % 20in % 20 Android % 20App

The code is like this:

 

Try {

    // android.os.Exec is not included in android.jar so we need to use reflection.    Class<?> execClass = Class.forName("android.os.Exec");    Method createSubprocess = execClass.getMethod("createSubprocess",            String.class, String.class, String.class, int[].class);    Method waitFor = execClass.getMethod("waitFor", int.class);        // Executes the command.    // NOTE: createSubprocess() is asynchronous.    int[] pid = new int[1];    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke( null, "/system/bin/ls", "/sdcard", null, pid);        // Reads stdout.    // NOTE: You can write to stdin of the command using new FileOutputStream(fd).    FileInputStream in = new FileInputStream(fd);    BufferedReader reader = new BufferedReader(new InputStreamReader(in));    String output = "";    try {        String line;        while ((line = reader.readLine()) != null) {            output += line + "/n";        }    } catch (IOException e) {        // It seems IOException is thrown when it reaches EOF.    }        // Waits for the command to finish.    waitFor.invoke(null, pid[0]);        return output;} catch( ... )
...

This method uses the Android. OS. Exec class provided by android. In the source code of Android, an ap similar to terminal is provided.

In/development/apps/Term/src/com/android/term, this ap uses android. OS. Exec to call basic linux commands. However, this class can only be used in the built-in ap of Android. If you write a non-built-in ap separately, you cannot directly call android. OS. Exec. The indirect method is similar to the above, using Class. forName ("android. OS. exec ") to obtain this class, execClass. getMethod ("createSubprocess ",...) to obtain the methods in the class, so that you can use classes that are not usable. Is this reflection ?...

 

This method seems to be a little troublesome and awkward. I think it is better to use java to provide something. After all, it is simple and portable.

 

As for how to put a self-written binary execution program into the apk and how to call it, the original post also makes it clear, but please note that the assets folder has a limit of 1 MB for a single file. so if there are resource files larger than 1 MB, I think I have to cut them first, and then work together when running them...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.