简体   繁体   中英

Execute commands via C code in Android

I want to execute the screenshot command "adb shell /system/bin/screencap -p /sdcard/img.png" into C. I was searching for the same and I got a solution for another command and I modified the command as

execl("/system/bin/screencap", "-p", "storage/sdcard0/screenShot.png", (char *)NULL);

but when I run my application and call method of above command, application gets crash.

How should I modify the " /system/bin/screencap -p /sdcard/img.png " command to run from C code.


Update after tom answer

Application is getting closed again and here is log

06-21 11:52:01.488: I/WindowState(279): WIN DEATH: Window{40fed2c0 u0 com.mytest.ndktestapplication/com.mytest.ndktestapplication.MainActivity}
06-21 11:52:01.498: I/ActivityManager(279): Process com.mytest.ndktestapplication (pid 7745) has died.
06-21 11:52:01.498: W/ActivityManager(279): Force removing ActivityRecord{40ea9ab8 u0 com.mytest.ndktestapplication/.MainActivity}: app died, no saved state

This is the expected result of exec() family functions.

What they do is replace the current program with the specified one. So bye-bye app.

To avoid that you would first need to call fork(), and then call exec() only in the child, something like this:

if (!fork()) {
    // fork() returned zero, so we are in the child
    execl...
}

You might also have to do some cleanup before calling the exec function.

Note however that you will not be able to take a screenshot from an app on most devices, as application code runs under a user id which lacks the permission to do so. But I seem to recall that there was a narrow period where some devices shipped without permission checks on this functionality, so it might work on those.

The invocation is

execl(path, arg0, arg1, ..., (char*) NULL);

The second argument, arg0 , is the name the program is told was used to invoke it. The actual arguments given to the program only start at arg1 .

So you should change your code to

execl("/system/bin/screencap", "screencap", "-p", "<pic>", (char *)NULL);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM