libgdx/Android:应用程序被销毁/暂停后图形消失

dan*_*aze 5 java android textures opengl-es libgdx

我正在做一些测试,我意识到在我的 Nexus 5 上,当我按下后退键(或主页)时 -也就是说,当上下文发生变化时- 并且我返回到我的游戏时,openGL 上下文会丢失。

不再有纹理(它们显示为黑色)或 UI 皮肤(按钮为白色)。

我以为它是由 libgdx 自动管理的,对吧?那么为什么会发生这种情况呢?

我创建纹理的方式是 via TextureAtlas,就像

TextureAtlas atlas;
TextureRegion bg;
atlas = new TextureAtlas(Gdx.files.internal("mainMenu.atlas"));
bg = atlas.findRegion("bg");
Run Code Online (Sandbox Code Playgroud)

然后它与batch.draw(bg, x, y, w, h);

我还尝试TextureRegion直接创建加载纹理而不是TextureAtlas(以防万一,但它应该是相同的),我得到了相同的结果......

任何人?

编辑:更具体的代码:

屏幕类基础知识:

public class MainMenuScreen extends ScreenManager.Screen {

        private Game game;
    private InputMultiplexer inputMultiplexer = new InputMultiplexer();

    private MainMenuUi screenUi;
    private MainMenuView screenView;

    private TextureAtlas atlas;

    public MainMenuScreen(ConbiniGame game) {
        this.game = game;

        atlas = new TextureAtlas(Gdx.files.internal("mainMenu.atlas"));
        screenUi = new MainMenuUi(game);
        screenView = new MainMenuView(atlas);

        inputMultiplexer.addProcessor(screenUi.getInputProcessor());
        inputMultiplexer.addProcessor(screenView.getInputProcessor());

        Gdx.input.setInputProcessor(inputMultiplexer);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

使用TextureAtlas的MainMenuView类...

public class MainMenuView {

    private Stage stage;
    private OrthographicCamera camera;
    private Viewport viewport;

    private TextureAtlas atlas;
    TextureRegion bg;

    public MainMenuView(TextureAtlas atlas) {
        atlas = atlas;
        bg = atlas.findRegion("bg");

        camera = new OrthographicCamera();
        camera.setToOrtho(false);
        viewport = new FitViewport(1080, 1920, camera);
        stage = new Stage(viewport);
    }

    public void update(float delta) {
        stage.act(delta);
    }

    public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.getBatch().begin();
        stage.getBatch().draw(bg, 0, 0, stage.getCamera().viewportWidth, stage.getCamera().viewportHeight);
        stage.getBatch().end();

        stage.draw();
    }

    public InputProcessor getInputProcessor() {
        return stage;
    }
}
Run Code Online (Sandbox Code Playgroud)

代码只是展示纹理的使用,其他部分都被删除了

Xop*_*ppa 4

您没有提供足够的信息,但您的问题可能是由static代码中的使用引起的。不要那样做。

当您按下后退按钮时,您的应用程序将关闭。当您按下主页按钮时,您的应用程序将暂停。请注意,这是两个不同的事情。因此,您在使用主页按钮时可能并不总是遇到这个问题。这是因为当您的应用程序暂停时,Android 可能会决定关闭它(以释放内存),但不能保证这样做。

不管怎样,这与 opengl 上下文丢失无关。它刚刚关闭。如果上下文确实丢失了,那么 libgdx(以及更高版本的 android)将为您恢复它。

当您关闭应用程序然后立即再次启动它时,Android 可能会为您的应用程序实例重用相同的虚拟机。这也意味着任何static变量都将具有应用程序上次运行时的值。如果这些变量中的任何一个包含(可能是间接的)任何资源,那么这些资源将不再有效。

tl;dr 从未static在 Android 应用程序中使用过。

最常见的错误(没有看到你的代码,这只是猜测)是使用单例访问资产。例如MyGame.getInstance().assets.get("atlas",...);,不要这样做,它会(由于上述原因)失败。相反,将对您的实例的引用传递MyGame给任何需要它的类(例如您的Screen: new MenuScreen(this);)。