我建议使用 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”回调,注册接收器等。在这个例子中,使用文件路径来确定哪个文件应该更新它的进度视觉。
不要忘记在清单中注册服务。
<service android:name="yourpackage.FileDownloader" />
笔记:
使用此解决方案,您可以立即为每个文件启动服务,并在每个服务报告新进度时随意处理传入的广播。在开始下一个文件之前,无需等待下载每个文件。但是,如果您坚持串行下载文件,您当然可以等待 100% 的进度回调,然后再调用下一个。
使用“回调字符串”
您可以在 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借来的示例代码