Интерфейс - это путь к go, поскольку вы не можете получить доступ к Android, указанному c коду из Core модуля.
Шаг 1: Создайте интерфейс (CORE MODULE)
public interface MyInterface {
void manipulateContext();
void manipulateContextWithExtraParams(String example, int example2);
}
Шаг 2: Реализуйте интерфейс (ANDROID MODULE)
import android.content.Context;
public class InterfaceImplementation implements MyInterface {
private Context context;
public InterfaceImplementation(Context context) {
// Store the context for later use
this.context = context;
}
@Override
public void manipulateContext() {
// Do something with the context, this is called on the core module
System.out.println(context);
}
@Override
public void manipulateContextWithExtraParams(String example, int example2) {
if (example2 == 1) {
System.out.println(example + context);
} else {
System.out.println(example);
}
}
}
Шаг 3: Отправьте реализованный интерфейс вашей игре (ANDROID МОДУЛЬ)
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.frontanilla.helping.getcontext.InterfaceImplementation;
import com.frontanilla.helping.getcontext.MyGame;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
InterfaceImplementation interfaceImplementation = new InterfaceImplementation(this);
// Here we send the implementation to our Game in Core module
initialize(new MyGame(interfaceImplementation), config);
}
}
Шаг 4: Сохраните и используйте методы, которые вы определили в вашем интерфейсе (CORE MODULE)
import com.badlogic.gdx.Game;
public class MyGame extends Game {
private MyInterface myInterface;
public MyGame(MyInterface myInterface) {
// Store for later use
this.myInterface = myInterface;
}
@Override
public void create() {
// Example of manipulating the Android Context indirectly from Core module
myInterface.manipulateContext();
myInterface.manipulateContextWithExtraParams("Hello", 2);
}
}
Как вы можете видеть, вы не будете манипулировать Context
непосредственно из основного модуля, вместо этого поместите эти логики c в InterfaceImplementation
класс