Run certain code only when in Android Mode

edited March 2018 in Android Mode

How do people run code that is only relevant when running on a phone?

For example I want my sketch look the same in Java and in Android mode. For this I have to use a strokeWeight that is proportional to displayDensity. Problem is the this variable is only available in Android mode. Similarly I only want to call size(width, height) in Java mode.

I can check for Android ...

if (System.getProperty("java.vendor") == "The Android Project") { strokeWeight(3*displayDensity) }

... but this will not compile because Java. In Javascript/Python this would just work because lazy evaluation and in C++ this could be done with #defines.

How do you do that in Processing/Java. Anybody knows a trick to make it work? Reflection module (looks crazy verbose)?

Let me know, Best,

Answers

  • edited February 2018 Answer ✓

    Ok, figured it out, semi-elegantly ...

    I am using the settings method so I can run code before size():

    void settings() {
      if (System.getProperty("java.vendor") == "The Android Project") {
        isAndroid = true;
      } else {
        isAndroid = false;
      }
    
      if (!isAndroid) {
        size(600,1000);
      }
    }
    

    Then in other locations I do:

      if (isAndroid) {
        strokeWeight(3*getValue("displayDensity"));
        // println(callMethodBoolean("hasPermission", "android.permission.ACCESS_FINE_LOCATION"));
      } else {
        strokeWeight(3);
      }
    

    getValue is my method that uses Refection to access the field dynamically:

    float getValue(String name) {
      float val = 0;
      try {
        val =  (float) this.getClass().getField(name).get(this);
      } catch (Exception e) {
        System.out.println(e);
      }
      return val;
    }
    

    I have some similar methods for doing dynamic method calls:

    void callMethodVoid(String name) {
      try {
        this.getClass().getMethod(name, null).invoke(this);
      } catch(Exception e) {
        System.out.println(e);
      }
    }
    
    float callMethodFloat(String name) {
      float val = 0;
      try {
        val =  (float) this.getClass().getMethod(name, null).invoke(this);
      } catch(Exception e) {
        System.out.println(e);
      }
      return val;
    }
    
    boolean callMethodBoolean(String name, String arg) {
      boolean val = false;
      try {
        val =  (boolean) this.getClass().getMethod(name, String.class).invoke(this, arg);
      } catch(Exception e) {
        System.out.println(e);
      }
      return val;
    }
    
  • thanks for sharing your solution, i was searching for that kind of stuff for a long time

Sign In or Register to comment.