For how long do static objects preserve their inst

2019-07-20 22:10发布

问题:

So I used a bit of a hack to preserve the state of a WebView in a Fragment.

private enum WebViewStateHolder
{
    INSTANCE;

    private Bundle bundle;

    public void saveWebViewState(WebView webView)
    {
        bundle = new Bundle();
        webView.saveState(bundle);
    }

    public Bundle getBundle()
    {
        return bundle;
    }
}

Then

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.activity_example, container, false);
    ButterKnife.inject(this, rootView);
    ...
    if(WebViewStateHolder.INSTANCE.getBundle() == null)
    {
        webView.loadUrl("file:///android_asset/index2.html");
    }
    else
    {
        webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
    }
    return rootView;
}

And

@Override
public void onPause()
{
    ...
    WebViewStateHolder.INSTANCE.saveWebViewState(webView);
    super.onPause();
}

So basically I save out the bundle on pause, then when the Fragment creates a view and this is not null, I load it back. It works perfectly okay, actually. However, if I say

getActivity().finish();

The WebView loads its data back from the bundle itself, still remembering the history of where it was.

This doesn't seem too reliable, and while this is a result of a test, I was still surprised that this happened.

When does a static object lose its data on Android? How long do these instances exist? Does Android get rid of them over time?

回答1:

The static variable will exist until your process is terminated.



回答2:

The static variable will exists until you class will be unloaded, so for example when you kill your activity or it will be killed because of memory issues