简体   繁体   中英

How to prevent restarting from orientation change?

Here is the structure of my application.

MainActivity.java calls FragmentActivity.java,
FragmentActivity.java calls GameView.java
GameView.java calls Thread.java.

Basically all the gaming logic will be handled by GameView and its thread. I don't know how to prevent from restarting the game when there is a orientation change.

If i paused the thread and resume it, the app crashes and also i can not use onSaveInstanceState method in Gameview.java

Any help?

It is completely possible through the Android manifest. Just add in the activity declaration, in which you want to disable the restarting the following attribute:

android:configChanges="orientation|screenSize"

Then you can overwrite the onConfigurationChanged() in your activity and you get the callback which event just happened. In your case the orientation change. And with this approach the activity doesn't restart, when your orientation changes.

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

您正在寻找onResume()和pause()...。您将值存储在bundle中,并在pause中实例化这些值,并在resume方法上实例化这些值,并在发生这种情况时显示一个对话框,以防止用户注意到明显的情况。

You can have some control over what happens on orientation change, by defining an Application class in your manifest file, and overriding public method onConfigurationChanged() .

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

You just need to check for newConfig == Configuration.ORIENTATION_LANDSCAPE and such. At this point you might want to reload resources to get things working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM