Search code examples
androiddownloadandroid-download-managerdownload-manager

android download manager download file once


I have below codes that when button clicked start download file, but the problem is when i click button multiple times it keep downloading the same file multiple times.How can i prevent that? which code should i add and where ?

    Button download= (Button)findViewById(R.id.download);
    download.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String path="http://xxxx.com/sound/ok.mp3";
            file_download(path);
        }
    });
                 }
     public void file_download(String uRl) {
     File direct = new File(Environment.getExternalStorageDirectory()
            + "/yebo");

    if (!direct.exists()) {
        direct.mkdirs();
    }

    DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

    Uri downloadUri = Uri.parse(uRl);
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
            | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle("pic")
            .setDescription("Downloading,Please Wait ...")
            .setDestinationInExternalPublicDir("/yebo", "mimi.mp3");
             mgr.enqueue(request);

}

Solution

  • use below code.

          public void onClick(View view) {
    
                            String path="http://xxxx.com/sound/ok.mp3";
                            file_download(path);
    download.setEnable(false);
    
                        }
    

    if you do not want to disable your button then u can set a flag like:

    int flag = 0;
     public void onClick(View view) {
    if(flag == 0)
    {                String path="http://xxxx.com/sound/ok.mp3";
                    file_download(path);
    flag += 1;
    }
    
    
                }