gpt4 book ai didi

Android 依次下载多个文件并在ListView中显示进度

转载 作者:太空狗 更新时间:2023-10-29 14:18:27 25 4
gpt4 key购买 nike

用户可以添加任意数量的下载,但下载会一个接一个开始,即下一次下载只有在本次下载完成后才会开始。用户将导航离开显示下载进度的 Activity 以添加新的下载,并且当添加要下载的新文件时,应用程序导航回到显示下载进度的 Activity,它将显示下载进度,之前添加,并将当前添加的文件保留为待下载。下载完成后,挂起的下载将立即开始下载。通过这种方式,用户可以添加任意数量的下载,它们将一个接一个地开始。我想在后台连续下载它们 - 一个接一个。我想在 ListView 中显示进度和状态。所以,ListView 看起来像:

文件 1 ...进行中说 39%

文件 2....待定

文件 3...待定

File4...待定

最佳答案

我建议使用 IntentServices:

public class FileDownloader extends IntentService {

private static final String TAG = FileDownloader.class.getName();



public FileDownloader() {
super("FileDownloader");
}

@Override
protected void onHandleIntent(Intent intent) {
String fileName = intent.getStringExtra("Filename");
String folderPath = intent.getStringExtra("Path");
String callBackIntent = intent
.getStringExtra("CallbackString");

// Code for downloading

// When you want to update progress call the sendCallback method

}

private void sendCallback(String CallbackString, String path,
int progress) {

Intent i = new Intent(callBackIntent);
i.putExtra("Filepath", path);
i.putExtra("Progress", progress);
sendBroadcast(i);

}

}

然后要开始下载文件,只需执行以下操作:

Intent i = new Intent(context, FileDownloader.class);
i.putExtra("Path", folderpath);
i.putExtra("Filename", filename);
i.putExtra("CallbackString",
"progress_callback");
startService(i);

现在你应该像处理任何其他广播一样处理“progress_callback”回调,注册接收器等。在这个例子中,使用文件路径来确定哪个文件应该有它的进度视觉更新。

不要忘记在您的 list 中注册该服务。

 <service android:name="yourpackage.FileDownloader" />

注意:

使用此解决方案,您可以立即为每个文件启动一个服务,并在每个服务报告新进度时随意处理传入的广播。无需等待每个文件下载完毕再开始下一个。但如果您坚持要串行下载文件,您当然可以等待 100% 的进度回调,然后再调用下一个。

使用“CallbackString”

你可以在你的 Activity 中这样使用它:

private BroadcastReceiver receiver;

@Overrride
public void onCreate(Bundle savedInstanceState){

// your oncreate code

// starting the download service

Intent i = new Intent(context, FileDownloader.class);
i.putExtra("Path", folderpath);
i.putExtra("Filename", filename);
i.putExtra("CallbackString",
"progress_callback");
startService(i);

// register a receiver for callbacks
IntentFilter filter = new IntentFilter("progress_callback");

receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
Bundle b = intent.getExtras();
String filepath = b.getString("Filepath");
int progress = b.getInt("Progress");
// could be used to update a progress bar or show info somewhere in the Activity
}
}
registerReceiver(receiver, filter);
}

记得在onDestroy 方法中运行:

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}

请注意,“progress_callback”可以是您选择的任何其他字符串。

示例代码借自 Programmatically register a broadcast receiver

关于Android 依次下载多个文件并在ListView中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19291462/

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