我建議使用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%進度回調。
使用 'CallbackString'
您可以使用它像這樣在你的活動:
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
考慮使用的AsyncTask借來的,但不知道如何表達下載完成後,開始爲下一個待處理的下載進度條。另外,如果用戶導航到其他活動以添加新下載,如何保持進度欄更新。 – user2416657