user4725754
user4725754

Reputation:

libGDX interfaces for native android code

I would like to use native android code in my project with help of an interface.

AndroidLauncher:

public int getNetworkState() {
    int a;

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi.isConnected()) {
        a=1;
    } else {
        a=0;
    }

    return a;
}

Core:

public interface NetworkState {
    public int getNetworkState();

}

How can I get the exact integer value in core project?

Upvotes: 2

Views: 1060

Answers (1)

Michaël Demey
Michaël Demey

Reputation: 1577

This is solved by doing the following:

Put your platform specific code in a class that implements your interface and have your Game class accept the interface as a parameter in its constructor.

So in your core project, you have your Game class;

public class GameInstance extends Game {
    private NetworkState networkState;

    public GameInstance(NetworkState networkState) {
        this.networkState = networkState;
    }

    // override methods go below
    ...
}

Also, you put your NetworkState interface in the core:

public interface NetworkState {
    public int getNetworkState();    
}

In your Android project you put the implementation;

public AndroidNetworkState implements NetworkState {
    public int getNetworkState() {
        return 1;
    }
}

And then in your AndroidLauncher you create a Game object and pass it the interface implementation:

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    NetworkState networkState = new AndroidNetworkState(); // or whatever you called the class
    initialize(new Game(networkState), config);
}

And then you can just call the interface method in your core project:

...
int networkStateResult = this.networkState.getNetworkState();
...

Be sure to provide implementations for other platforms if you support other platforms.

Upvotes: 3

Related Questions