Issue
I'm writing a C program which I want to execute on my Desktop running Linux and also on an Android device.
I have to make some Desktop specific things and some Android specific things.
My question is, is there a way to get the OS version in C so I can handle if the program is executed on the Desktop or on the Android device?
Solution
In your native code, you could use property_get()
, something like this:
#include <cutils/properties.h>
// ...
int myfunction() {
char sdk_ver_str[PROPERTY_VALUE_MAX] = "0";
property_get("ro.build.version.sdk", sdk_ver_str, "0");
sdk_ver = atoi(sdk_ver_str);
// ...
}
On desktop, property_get()
should return empty string.
Note that in starting from Android 6, <cutils/properties.h>
is not available in SDK, use __system_property_get
as follows:
#include <sys/system_properties.h>
// ...
int myfunction() {
char sdk_ver_str[PROPERTY_VALUE_MAX];
if (__system_property_get("ro.build.version.sdk", sdk_ver_str)) {
sdk_ver = atoi(sdk_ver_str);
} else {
// Not running on Android or SDK version is not available
// ...
}
// ...
}
You can use adb shell getprop
to see all possible Android properties. But, be aware that not all of them are supported by all devices.
UPDATE: If you don't need OS version, but simply want to tell if your C/C++ code is running on Android, very simple way to tell is to check if environment variable ANDROID_PROPERTY_WORKSPACE
exists (on Android 7 or older), or if socket /dev/socket/property_service
exists (Android 8 or newer), something like this:
include <stdlib.h>
include <unistd.h>
// ...
if (getenv("ANDROID_PROPERTY_WORKSPACE")) {
// running under Android 7 or older
} else if (access("/dev/socket/property_service", F_OK) == 0) {
// running under Android 8 or newer
} else {
// running on desktop
}
Answered By - mvp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.