简体   繁体   English

如何停止下载管理器下载我的下载文件中已经存在的文件?

[英]How do i stop the download manager downloads a file that already exists in my downloads?

I am a new in android development.I created a webview in my android app that has a downloadable file.I was able to download the file, but each time I download the file it downloads again even if it exists in my downloads. 我是android开发的新手。我在android应用中创建了一个可下载文件的webview。我能够下载该文件,但是每次下载该文件时,即使该下载文件中存在该文件,它也会再次下载。

This is the MainActivity with the DownloadManager. 这是带有DownloadManager的MainActivity。

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;



public class MainActivity extends AppCompatActivity
{
    WebView mWebView;

    SwipeRefreshLayout swipe;
    private Activity mActivity;
    private Context mContext;

    private static final int MY_PERMISSION_REQUEST_CODE = 123;



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


        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            public void onRefresh(){
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb()
    {
        mContext = getApplicationContext();
        mActivity = MainActivity.this;
        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.setHorizontalScrollBarEnabled(true);
       final  String url = "https://www.conquestcapitalltd.com/";
        mWebView.loadUrl(url);
        swipe.setRefreshing(true);
        checkPermission();
        mWebView.setWebViewClient(new WebViewClient() {

           //public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
             //   mWebView.loadUrl("file://android_asset/error.html");
            //}

            public void onPageFinished(WebView view, String url)
            {
                //hide the swipe refreshlayout
                swipe.setRefreshing(false);
            }

        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDescription,
                                        String mimetype, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(
                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                String fileName = URLUtil.guessFileName(url,contentDescription,mimetype);
                 if (fileName != null && !TextUtils.isEmpty(fileName)) {
                 File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DOWNLOADS,"/"+fileName);
                if (file.exists()) {
                  return;
                 }
                else{
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);

                DownloadManager dManager =(DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dManager.enqueue(request);
                Toast.makeText(getApplicationContext(), "Downloading File...", Toast.LENGTH_LONG).show();
               }
            }
        });

    }

    protected void checkPermission() {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                if(shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                    //Alert Dialog
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("Write external storage permission is required.");
                    builder.setTitle("Please grant permission");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions(mActivity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    MY_PERMISSION_REQUEST_CODE
                            );
                        }
                    });
                    builder.setNeutralButton("Cancel",null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else{
                    ActivityCompat.requestPermissions(
                            mActivity,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSION_REQUEST_CODE
                    );
                }
            }else {
                //permission already granted
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSION_REQUEST_CODE:{
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            }else{
                //permission denied
                    }
            }
        }
    }

    @Override
    public boolean onKeyDown(final int keyCode, final KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

I expect the DownloadManager to only download the file from the website once. 我希望DownloadManager仅从网站下载一次文件。

Try this 尝试这个

private void isFileDownloaded(String fileName) {
    if (fileName != null && !TextUtils.isEmpty(fileName)) {
        File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DOWNLOADS,"/"+fileName);
        if (file.exists()) {
            return;
        } else {
            // write here code for download new file
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM