【问题标题】:android download manager download file onceandroid下载管理器下载文件一次
【发布时间】:2017-05-09 18:51:12
【问题描述】:

我有以下代码,当按钮单击开始下载文件时,但问题是当我多次单击按钮时,它会多次下载同一个文件。我该如何防止这种情况发生?我应该添加哪些代码以及在哪里添加?

    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);

}

【问题讨论】:

    标签: android download android-download-manager download-manager


    【解决方案1】:

    使用下面的代码。

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

    如果您不想禁用按钮,则可以设置如下标志:

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

    【讨论】:

      【解决方案2】:

      您可以禁用 Button 并在完成后重新启用它,例如

       final Button download= (Button)findViewById(R.id.download);
       @Override
       public void onClick(View view) {
            download.setEnabled(false);
            download.setAlpha(.2f); // grey it out
            String path="http://xxxx.com/sound/ok.mp3";
            file_download(path);
       }
      

      【讨论】:

      • @f2k 没问题。如果对您有帮助,请不要忘记接受此答案。
      猜你喜欢
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      相关资源
      最近更新 更多