簡體   English   中英

保存/恢復android webview的狀態

[英]save/restore state of android webview

我有一個簡單的 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();
}

恢復您的應用程序后,應用locationManager.getLastKnownLocation以獲取最后存儲的位置並將其注入您的 webview 的 javascript 中。 僅當locationManagernull時才應執行此操作。 而且locationManager會耗盡電池電量,當用戶不積極使用應用程序時,最好不要使用它。

除了上面的代碼之外,啟用以下屬性就像一個魅力:)

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

對於 AndroidManifest.xml 中包含 WebView 的每個活動都為我工作。 盡管這是一個通用的答案,但可以解決您和許多其他此類人遇到的問題。

即使savedInstanceState != null你不應該設置你的myLocationManager和其他實例變量嗎?

恢復WebView狀態不會為您執行此操作,並且您的應用程序在嘗試取消對其中一個的引用時可能會崩潰,從而為您提供NullPointerException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM