保存/恢复android webview的状态

问题描述 投票:0回答:3

我有一个简单的 webView 应用程序,它从我们的网站加载一个页面,其中包含我们的现场人员每天应该访问的位置和电话号码。它提供了一个启动导航或拨打电话的挂钩。从外部活动返回时,应用程序崩溃。点击手机的主页按钮,然后拨打电话,然后返回到应用程序,效果很好。

这是代码...

更新 2 - 不再崩溃,返回时 webview 为空白

public class VSIMobile_WebView extends Activity {
private static String PROVIDER="gps";
private WebView browser;
private LocationManager myLocationManager=null;
private TelephonyManager myTeleManager = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    browser=(WebView)findViewById(R.id.webview);
    myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    myTeleManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.addJavascriptInterface(new Locater(), "locater");
    browser.addJavascriptInterface(new JavaScriptInterface(this), "Android");
    if (savedInstanceState!=null){
        browser.restoreState(savedInstanceState);
    }else{ 
        browser.loadUrl("http://zzz.com");
        browser.setWebViewClient(new HelloWebViewClient());
    }
}

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

@Override
public void onSaveInstanceState(Bundle outState) {
    //Toast.makeText(getBaseContext(), browser.getUrl(), Toast.LENGTH_LONG).show();
    browser.saveState(outState);
} 

@Override
protected void onRestoreInstanceState(Bundle state) {
    browser.restoreState(state);
    super.onRestoreInstanceState(state);
    //Toast.makeText(getBaseContext(), browser.getUrl(), Toast.LENGTH_LONG).show();
}


/* Did not work
public void onResume(Bundle inState){
    browser.restoreState(inState);
    super.onResume();   
}
public void onPause(Bundle outState) {
    browser.saveState(outState);
    super.onPause();
}
*/


@Override
public void onResume(){
    super.onResume();   
}


@Override
public void onPause() {
    super.onPause();
}
android android-activity webview
3个回答
0
投票

即使

myLocationManager
,您不应该设置
savedInstanceState != null
和其他实例变量吗?

恢复

WebView
状态不会为你做到这一点,并且当你的应用程序尝试取消引用其中一个时,它可能会崩溃,给你一个
NullPointerException


0
投票

启用以下属性,除了上面的代码之外,它的作用就像一个魅力:)

android:launchMode="singleInstance"
android:alwaysRetainTaskState="true"

对于 AndroidManifest.xml 中包含 WebView 的每个活动,都对我有用。尽管这是一个普遍的答案,但可以解决您和许多其他遇到此问题的人。


0
投票

恢复您的应用程序后,应用

locationManager.getLastKnownLocation
获取最后存储的位置并将其注入到您的 webview 的 javascript 中。仅当
locationManager
null
时才应执行此操作。而且
locationManager
会消耗电池电量,当用户不积极使用该应用程序时,最好不要使用它。

© www.soinside.com 2019 - 2024. All rights reserved.