【问题标题】:saving webview into local storage automatically将 webview 自动保存到本地存储中
【发布时间】:2020-05-23 11:58:18
【问题描述】:

Webview 每次打开时都会加载,有什么方法可以在我第一次打开时将 Web 视图文件保存在本地存储中,当我再次打开时,它们不需要下载。意味着即使没有互联网它们也会打开。

这是我的 java 文件。我们有什么办法可以完成这项任务

package com.example.impwala;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;



public class chemistry1 extends AppCompatActivity {

    WebView chem1;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chemistry1);

        if (haveNetwork())
        {
            init();
            listener();
        }
        else if (!haveNetwork())
        {
            AlertDialog.Builder builder =new AlertDialog.Builder(this);
            builder.setTitle("No internet Connection");
            builder.setMessage("Please turn on internet connection to continue");
            builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();        }

    }

    public boolean haveNetwork()
    {
        boolean have_WIFI=false;
        boolean have_MobileData=false;

        ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos=connectivityManager.getAllNetworkInfo();

        for (NetworkInfo info:networkInfos)
        {
            if (info.getTypeName().equalsIgnoreCase("WIFI"))
                if(info.isConnected())
                    have_WIFI=true;
            if (info.getTypeName().equalsIgnoreCase("MOBILE"))
                if(info.isConnected())
                    have_MobileData=true;
        }
        return have_MobileData||have_WIFI;
    }
    private void init() {

        chem1 = (WebView) findViewById(R.id.chem1);
        chem1.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(chemistry1.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        chem1.loadUrl("www.example.com");

    }


    private void listener() {
        chem1.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}

【问题讨论】:

    标签: java android performance webview download


    【解决方案1】:

    将您的页面作为网络存档保存到公共文档文件夹中的 SD 卡存储中,

    File file;
    String filenameExternal = "mypage";
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED{
             file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), filenameExternal);
    }
    
    chem1.saveWebArchive(file.toString()+".mht");
    

    然后,当用户通过覆盖@OnStop 方法离开应用程序时,使用共享首选项保存文件名/路径。 最后,当用户重新打开应用程序时,通过从共享首选项中读取文件路径来加载您保存的页面。

    if (Build.VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
                        chem1.loadUrl(file.toString()+".mht");
                    } else {
    
                        loadOfflinePageBelowKitKat(position);
                    } 
    

    loadOfflinePageBelowKitKat 方法

    public void loadOfflinePageBelowKitKat(){
    
        String rawData = null;
        try{
            rawData = getStringFromFile(file.toString()+".mht");
        }catch (Exception e){
            e.printStackTrace();
        }
    
        chem1.loadDataWithBaseURL(null, rawData, "application/x-webarchive-xml", "UTF-8", null);
    
    }
    

    getStringFromFile 方法

    public String getStringFromFile(String filePath) throws Exception{
        File file = new File(filePath);
        FileInputStream fInputStream = new FileInputStream(file);
        String wantedString = convertStreamToString(fInputStream);
        fInputStream.close();
        return  wantedString;
    }
    

    我假设您熟悉处理共享首选项和文件。

    【讨论】:

    • 其实不熟悉共享首选项和文件,我是新手
    • 别担心!使用共享偏好非常容易。检查此链接developer.android.com/training/data-storage/shared-preferences 并使用将文件保存/读取到本地存储/从本地存储检查此链接androidauthority.com/…
    • 我无法从链接中理解,请告诉我将哪些代码放在哪里,但这会有所帮助。
    • 我已经更新了我的答案,包括如何将网页保存到外部存储,看看吧!
    • 您应该将变量声明为private File file; private String fileNameExternal = "mypage"; 的成员变量,然后if 语句必须在onCreate() 方法中。最后在onStop()方法中调用chem1.saveWebArchive(file.toString()+".mht");。我对 getExternalStorateState 做了一些错字,它应该是 getExternalStorageState。
    猜你喜欢
    • 2018-11-05
    • 2016-04-29
    • 2021-12-06
    • 2014-07-07
    • 2022-01-23
    • 2018-11-20
    • 2017-09-22
    • 2022-10-02
    相关资源
    最近更新 更多