1

I am making a game for both android and pc, and have to import stuff exclusive to android along with write methods containing code that only works with android

I want to be able to do something like this, so in the case of me compiling for a non-android version, it wont give compile errors

boolean android = "The Android Project".equals(System.getProperty("java.specification.vendor"));
void setup(){
    if (android)
        importAndroid();
    //other setup stuff irrelevant to the question
}

void importAndroid(){
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    import android.content.Context;
    import android.app.Activity;
}
jww
  • 97,681
  • 90
  • 411
  • 885
F53
  • 41
  • 1
  • 5
  • Possible duplicate of [How to determine if my app is running on Android](https://stackoverflow.com/q/4519556/608639), [How do I programmatically determine operating system in Java?](https://stackoverflow.com/q/228477/608639), etc. – jww Oct 04 '19 at 02:59

1 Answers1

1

You can't conditionally import classes like that.

Instead, you should encapsulate the code that runs on both desktop and Java into its own class (or multiple classes), which you can use as a library. Then build a desktop application and an Android app that contain the code specific to just one version. Both platform-specific projects would use the shared code as a library.

If you need to call platform-specific code from the shared code, then do so through an interface so you don't have to care about platform-specific code in your shared code. Something like this:

public interface Printer {
  public void print(String s);
}

Then implement platform-specific code in implementations of that interface:

public class DesktopPrinter implements Printer {
  public void print(String s) {
    System.out.println(s);
  }
}


public class AndroidPrinter implements Printer {
  public void print(String s) {
    Log.d("MyApp", s);
  }
}

Then in your Processing code, you would only ever use the interface:

Printer printer;

void setPrinter(Printer printer) {
  this.printer = printer;
}

void draw(){
  printer.print("in draw");
}

Then create an instance of these classes in the platform-specific code and pass it into your sketch class.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107