点击

时间:2017-02-06 13:35:56

标签: android webview hyperlink download

我有一个包含pdf超链接的webview(其中一些很大),当用户点击pdf开始下载的超链接,然后在pdf vieweR中查看。

我想添加一个取消按钮来停止正在进行的下载,这怎么可能? 如何停止正在进行的下载

1 个答案:

答案 0 :(得分:0)

管理下载的最佳和最简单的方法是使用DownloadManager。也 WebView提供了API来设置下载侦听器,这使得下载处理变得更加容易 - DownloadListener。 以下是通过单击按钮启动和取消下载的快速示例:

public class MainActivity extends AppCompatActivity {
    private Long mOnGoingDownload;
    private Button mCancel;
    private WebView mWebView;
    private DownloadManager mDownloadManger;

    protected void cancelDownload() {
        if (mOnGoingDownload != null) {
            mDownloadManger.remove(mOnGoingDownload);
            clearDownloadingState();
            Toast.makeText(this, "Download canceled", Toast.LENGTH_SHORT).show();
        }
    }

    protected void clearDownloadingState() {
        unregisterReceiver(mDownloadCompleteListener);
        mCancel.setVisibility(View.GONE);
        mOnGoingDownload = null;
    }

    BroadcastReceiver mDownloadCompleteListener = new BroadcastReceiver() {
        public void onReceive(Context ctx, Intent intent) {
            clearDownloadingState();
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            Uri fileUri = mDownloadManger.getUriForDownloadedFile(id);
            //Open file in viewer
            //...
            Toast.makeText(ctx, fileUri.getLastPathSegment() + " downloaded", Toast.LENGTH_SHORT).show();
        }
    };

    protected void startDownload(String url, String userAgent, String mimetype) {
        Uri fileUri = Uri.parse(url);
        String fileName = fileUri.getLastPathSegment();
        String cookies = CookieManager.getInstance().getCookie(url);

        DownloadManager.Request request = new DownloadManager.Request(fileUri);
        request.setMimeType(mimetype)
                .addRequestHeader("cookie", cookies)
                .addRequestHeader("User-Agent", userAgent)
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        //register receiver for download complete event
        registerReceiver(mDownloadCompleteListener, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        mCancel.setVisibility(View.VISIBLE);
        mOnGoingDownload = mDownloadManger.enqueue(request);
        Log.e("DownloadExample", "68|MainActivity::startDownload: Download of " + fileName + " started");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDownloadManger = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        mCancel = (Button)findViewById(R.id.cancelDownload);
        mCancel.setVisibility(View.GONE);
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelDownload();
            }
        });

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                startDownload(url, userAgent, mimetype);
            }
        });

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.engineerhammad.com/2015/04/Download-Test-Files.html");
    }
}

主要布局是:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.andrii.webview.MainActivity">
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </WebView>
    <Button
        android:layout_gravity="bottom"
        android:id="@+id/cancelDownload"
        android:layout_width="match_parent"
        android:text="Cancel donload"
        android:layout_height="wrap_content" />
</FrameLayout>