Prevent Reload Activity / Webview when go Back to

2019-09-10 02:22发布

问题:

I have a fragment inside of an Activity and then, inside of this fragment I also have a webview.

Problem: After lock my screen and unlock pressing the turn off button, my Activity is recreated or my webview is reloaded (not sure what happens).

The same problem occurs when I switch apps in my device.

I tried to change my configChanges and my launchMode. Here is part of my activity in android manifest file:

     <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTop"
        >
    </activity>

Also I tried to check my savedInstanceState on myCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (savedInstanceState == null) {
        this.init(); // Initialize my webview
    }
...

EDIT:

@Override
protected void onResume() {
    super.onResume();

    //Check if the user is authenticated onResume
    String message = getIntent().getStringExtra(MainActivity.FragmentIdentifier);

    if(message == null || message.compareTo(MainActivity.showWebViewFragment) == 0){
        changeFragment(new WebViewFragment());

    }else if (message.compareTo(MainActivity.showLoginFragment) == 0){
        changeFragment(new LoginFragment());
    }
}

Any ideas or code samples will be appreciated, thanks!

回答1:

I figured out that I should handle the Instance and check if already saved or not, otherwise my onResume could always reload my webview. Here my new code:

@Override
protected void onResume() {
    super.onResume();

    //Check if the user is authenticated onResume
    String message = getIntent().getStringExtra(MainActivity.FragmentIdentifier);

    if (message == null || message.compareTo(MainActivity.showWebViewFragment) == 0) {

        /*
         Check if the instance is saved. If yes, is not necessary to create a new instance of the webview,
         otherwise will always reload.
        */
        if (!getSavedInstance()){
            changeFragment(new WebViewFragment());
        }

    } else if (message.compareTo(MainActivity.showLoginFragment) == 0) {
        changeFragment(new LoginFragment());
    }

}

I declared a new global variable

private Boolean savedInstance = false;

And here my get and set

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    setSavedInstance(true);
}

public Boolean getSavedInstance() {
    return savedInstance;
}

public void setSavedInstance(Boolean instance_saved) {
    this.savedInstance = instance_saved;
}