无法将网页下载到sdcard android webview

时间:2018-09-26 02:40:43

标签: android webview

我的应用程序中有一个Web视图来显示Facebook链接,现在我想将页面保存为html文件并存储在SD卡中,以便离线时应用程序会将页面加载到用户。但是我无法下载吗?我不知道为什么当完成时,我使用异步任务下载和烘烤,但是什么也没显示。这是我的代码:

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

    findViewById();

    if (isNetworkConnected()) {
        mWebView.clearCache(true);
        mWebView.setWebViewClient(new myWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(downloadUrl);

        new DownloadFile().execute();
    } else {
        mWebView.loadUrl(Environment.getExternalStorageDirectory().toString() +
                "/Android/data/hao.com.webviewdemo/" + "webpage.html");
    }
}

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
}

private class DownloadFile extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl) {
        try {

            URL url = new URL(downloadUrl);
            URLConnection connection = url.openConnection();
            connection.connect();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() +
                    "/Android/data/hao.com.webviewdemo/" + "webpage.html");

            byte data[] = new byte[1024];
            int count;
            try {
                while ((count = input.read(data)) != -1)
                    output.write(data, 0, count);
            } catch (IOException e) {
                e.printStackTrace();
            }

            output.flush();
            output.close();
            input.close();

            Toast.makeText(MainActivity.this, "File downloaded", Toast.LENGTH_SHORT).show();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }
}

我在清单中的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

1 个答案:

答案 0 :(得分:0)

您尝试过这种方式下载网页吗?

^(?=(.*[a-zA-Z0-9]| +)).+

希望能为您提供帮助