Android在Java中设置(获取)环境变量 [英] Android set(get) environmental variables in Java

查看:436
本文介绍了Android在Java中设置(获取)环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Android OS进行了很少的尝试,并且尝试调用System.getenv()来获取环境变量.它可以例如对于$PATH,但是我无法定义自己的变量,可以通过这种方式访问​​...可能吗?

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?

我尝试以a shell用户的身份从adb shell设置和export变量,但是它不起作用-无论是从电话菜单启动应用程序还是何时使用adb shell am命令

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.

Runtime.getRuntime().exec()可以帮助您吗?如果我可以root访问电话,对您有帮助吗?

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

谢谢

推荐答案

环境变量仅在设置变量的进程中可见,而子进程在设置变量后启动.从adb shell设置环境变量时,您不在启动Android应用程序的进程的父进程中,因此该应用程序看不到您设置的变量.

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.

在Java(和Android)中没有System.setenv(),但是如果您需要为自己的程序设置环境变量以进行读取,则总会有更好的方法.一种这样的方法是设置和获取属性

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.

实际上不可能在Java中设置环境变量(可以,但是您不想这样做).如果要设置另一个进程应使用的变量,则可以使用 ProcessBuilder 阅读,但这就是从Java/Android程序启动该过程的原因.

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.

考虑您要解决的问题,以及是否可以在不使用环境变量的情况下完成.它们不是Java的理想选择,而在Android上则更糟.

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.

这篇关于Android在Java中设置(获取)环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆