How long do static objects keep their instances on Android?
So, I used a little hack to save the state of the WebView in the 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 keep the package paused and then when the Fragment creates the view and it's not null, I load it back in. In fact, everything works fine. However, if I say
getActivity().finish();
The WebView loads its data from the package itself, still remembering the history of where it was.
It doesn't seem too reliable, and while this is a test result, I still wondered what happened.
When does a static object lose its data on Android? How long have these specimens been around? Does Android remove them over time?
The static variable will continue to exist until your process exits .
The static variable will exist until the class is unloaded, for example when you kill your activity or it gets killed due to memory problems.