When rotating my screen I'm losing my connection to in app billing. This is my onDestroy method below:

@Override
    protected void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            Log.d(tag, "Destroying helper.");
            if (mHelper != null) {
                mHelper.dispose();
                mHelper = null;
            }
        }
        Toast.makeText(this, "onDestroy " + mHelper, Toast.LENGTH_SHORT).show();
    }

Which shows that mHelper is still not null when the screen orientation is changing as the activity is not finishing, then after this in my onCreate method, mHelper is null.

How can I prevent a screen rotation doing this?

有帮助吗?

解决方案

By default, an orientation change will cause the system to destroy and recreate your Activity, to change this behavior change the Activity's entry in AndroidManifest.xml:

<activity android:name=".MyActivity"
          android:configChanges="orientation"
          android:label="@string/app_name">

which tells Android that you wish handle configurations change yourself, so the Activity will not be restarted when an orientation change occur, but your current Activity instance's onConfigurationChanged() method will be called.

An example of singleton:

public class SingletonObjectDemo {

    private static SingletonObject singletonObject;
    // Note that the constructor is private
    private SingletonObjectDemo() {
        // Optional Code
    }
    public static SingletonObjectDemo getSingletonObject() {
        if (singletonObject == null) {
            singletonObject = new SingletonObjectDemo();
        }
        return singletonObject;
    }
}

You can check out more info on how orientation change is handled here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top