开发者

Android set(get) environmental variables in Java

I have experimented little with Android OS and I tried to call System.getenv() to get environmental variables. It works e.g. for $PATH, but I was not able to define own variable, which can be accessible in this way... Is it possible?

I have tried to set and export variables from adb shell as a shell user but it does not work - no matter if I started the application from the phone menu or when I used the adb shell am command.

Can the Runtime.getRuntime().exec() h开发者_StackOverflow社区elp there? Will it help if I will have root access to the phone?

Thanks


Environment variables are only visible in a process that sets the variable, and child processes launched after setting the variable. When you set the environment variable from the adb shell you are not in the parent process of the process that launches the Android application, so the application cannot see the variable you set.

In Java (and Android) there is no System.setenv(), but if you need to set an environment variable for your own program to read there are always better ways. One such way is setting and getting Properties instead.

Setting environment variables in Java is not really possible (well, it is, but you don't want to do it). You can use ProcessBuilder if you want to set a variable that another process should read, but that's if the process is launched from a Java/Android program.

Think about what problem you're trying to solve, and if it can be done without using environment variables. They're not a good fit in Java, and are even worse on Android.


It is possible to set environment variables in Android applications. However, as @richq said, those variables will be only visible in processes launched from the application that has set environment variable (and JNI libraries used by the application). See this post for regarding setting environment variables from Android application: https://stackoverflow.com/a/22315463/927592


Android API 21 provides a way to set the environment variables. To set an environment variable, invoke Os.setenv.

See this android.system.Os documentation and this setenv(3) documentation.

Each process has its own environment, which is copied from the parent process's environment. So the environment variables are per-process.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜