Search code examples
androidenvironment-variablesroot

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() help there? Will it help if I will have root access to the phone?

Thanks


Solution

  • 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.