Android sets (gets) environment variables in Java

I did not experiment much with Android, and I tried calling System.getenv() to get the environment variables. It works, for example. for $PATH , but I could not define my own variable that could be accessed this way ... Is this possible?

I tried to set export variables from adb shell as a shell user, but it does not work, regardless of whether I started the application from the phone menu or when I used the adb shell am command.

Does Runtime.getRuntime().exec() help? Will it help if I have access to the root phone?

thanks

+8
source share
3 answers

Environment variables are visible only in the process that sets the variable, and child processes start 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 specified.

There is no System.setenv() in Java (and Android), but if you need to set an environment variable for your own program to read, there are always better ways. One of these methods is setting and getting properties .

Setting environment variables in Java is actually not possible (well, it is, but you do not want to do this). You can use ProcessBuilder if you want to set a variable that another process should read, but what if the process starts with a Java / Android program.

Think about what problem you are trying to solve, and if it can be done without using environment variables. They are not well suited for Java, but on Android they are even worse.

+7
source

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

+4
source

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

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

Each process has its own environment, which is copied from the environment of the parent process. Thus, environment variables are for each process.

0
source

All Articles