4

For now I've used the classic export command to set an environment variable and tried to read this variable from my test with System.getenv() function, but it doesn't seem to work.

Can someone give an example how to set and read a system variable in an Android application?

Michalis
  • 3,109
  • 6
  • 26
  • 24
  • Please see http://stackoverflow.com/a/22315463/927592 for android-specific way to set/get environment variables from Java – Alex Cohn Jan 04 '15 at 13:18

4 Answers4

3

The env variable is only visible in processes that are descended from (or the same as) the process that sets the env variable value. (see http://en.wikipedia.org/wiki/Environment_variable#Synopsis)

This may be a factor in your apparent inability to see the value you set, if the process in which you want to read the value, is not a descendent of the process in which you set it.

So you need to examine the process hierarchy of your application(s) to determine where you should be setting the value.

MikeW
  • 41
  • 2
  • 1
    This is true. But I used the same Android shell to set the environment variable and execute my Android app. – Michalis Sep 23 '10 at 06:23
2

To get and set a property you could do the following:

System.getProperty('property_name');

System.setProperty('property_name', 'value');

System.getenv() should work for returning a map of all available environment variables.

Can you post some of your code if it still doesn't work?

xil3
  • 16,305
  • 8
  • 63
  • 97
  • I still can't make it work. This is how I export the system variable. `export A=123` and this is how I am trying to get the value : `tmp = System.getenv("A"); Log.d("MyTest","== A: " + tmp);` – Michalis Sep 20 '10 at 07:20
2

If you are familiar with using the NDK, simply create a native function in NDK space containing the line, or add it to an existing function.

setenv("ENVIROMENT_VARIABLE", "value", 1);

You can then use the java APIs System.getenv() to read it.

While this is cumbersome, it is necessary for using online code analysis tools like gcov (included with the android ndk) for code coverage.

miork2056
  • 21
  • 1
0

My initial purpose was read external arguments in my Android application. So I finally used XML file as a configuration file. This still is not an answer to my question but someone might find it helpful. See how to load an XML configuration file here

Michalis
  • 3,109
  • 6
  • 26
  • 24