开发者

How to determine if my app is running on Android [duplicate]

This question already has answers here: How do I programmatically determi开发者_如何学Cne operating system in Java? (22 answers) Closed 3 years ago.

I have an app that runs on several mobile devices running either Fedora or Android. To consolidate my codebase and distribution I would like to determine which OS I am on. I tried System.getProperty("os.name"), but that just returns "Linux". Is there something unique to Android in the System properties? Thanks


There are several properties you could check. Candidates are:

  • java.vendor.url --> http://www.android.com
  • java.vm.name --> Dalvik (I don't know, which one Fedora is using...)
  • java.vm.vendor --> The Android Project
  • java.vendor --> The Android Project

Maybe you want to check by yourself?

Properties p = System.getProperties();
Enumeration keys = p.keys();
while(keys.hasMoreElements()) {
   String key = (String) keys.nextElement();
   String value = (String) p.get(key);
   System.out.println(key + " >>>> " + value);
}


I do not know Android but if you do not find some unique system property you can sometimes identify the system if some specific class exists there. So you can do the following:

boolean isAndroid() {
    try {
        Class.forName("the class name");
        return true;
    } catch(ClassNotFoundException e) {
        return false;
    }
}


Here is some code that I wrote using the information from this page, in case you want to copy-paste:

private static YLogger ylogger;
public static YLogger getLogger() {
    if (ylogger == null){
        // need to find a new logger. Let's check if we have Android running
        if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")){
            ylogger = new AndroidLogger();
            ylogger.d("YLoggerFactory", "Instantiating Android-based logger");
        } else {
            // fallback option, system logger.
            ylogger = new SystemLogger();   
            ylogger.d("YLoggerFactory", "Instantiating System-based logger");
        }
    }
    return ylogger;
}


The list of defined system properties is here: https://developer.android.com/reference/java/lang/System#getProperties()

I'm using

boolean android = "The Android Project".equals(System.getProperty("java.specification.vendor"));


I use this in my processing sketch to determine in which mode I'm running i.e. where I'm running it.

enum Mode {
  java, android
}

Mode getMode() {
  return System.getProperty("java.runtime.name").equals("Android Runtime") ? Mode.android : Mode.java;
}

if (getMode() == Mode.java){
  // do something
  // eg: do something that android can't handle
} else {
  // do android stuff 
  // eg: scale the sketch by 2 to improve visibility
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜