gpt4 book ai didi

java - 使用 ProgressDialog 下载文件,取消下载 (Android)

转载 作者:行者123 更新时间:2023-12-02 00:02:56 25 4
gpt4 key购买 nike

下载文件时,我向用户显示此对话框,有取消按钮

    protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading ..");
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
<小时/>

我的下载代码是:

protected String doInBackground(String... aurl) {
int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(sunDir.getPath()
+ musicFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
}
return null;

}
<小时/>

我的问题是:

  • 当在文件下载对话框中按下取消按钮时,不要取消
  • 如果文件下载完成,我想当用户按下取消按钮时
    或者不完全删除文件

最佳答案

when press cancel button on dialog file downloading don't cancel

您将需要使用AsyncTask.cancel()要取消取消按钮上的 AsyncTask,请单击:

   public static boolean downloadstatus=true;
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
your_AsyncTask.cancel(true); //<<<<<
downloadstatus=false;
dialog.cancel();
}
});

I want to when user press cancel button if file downloaded complete or not delete file exactly

您需要检查 AsyncTask 是否在 doInBackground 内运行或取消,以停止文件下载:

    while ((count = input.read(data)) != -1) {
if(!your_AsyncTask.isCancelled() && downloadstatus !=false){
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
else{
// free all resources here
break;
}
}

关于java - 使用 ProgressDialog 下载文件,取消下载 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14483151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com