1

我有下面的代码,当按钮点击开始下载文件,但问题是当我点击按钮多次,它不断下载相同的文件多次times.I我可以防止?我应该添加哪些代码以及在哪里?安卓下载管理器下载文件一次

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

} 

回答

0

使用以下代码。

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


      } 
+0

谢谢@ singh.indolia它工作得很好 – f2k

+0

@ f2k最受欢迎。 –

0

您可以禁用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); 
} 
+0

非常感谢@Muratķ – f2k

+0

@ f2k没问题。如果它帮助你,请不要忘记接受这个答案。 –