依次下载和解压缩文件

时间:2014-11-05 07:07:48

标签: java android android-download-manager

方案:

活动启动服务以下载n个文件(zip文件)[n从10到60不等,每个文件的大小从100 kb到20 MB不等]发送List<String> urlsToBeDownloaded

在服务启动方法中,保存第一个文件以供下载,一旦下载文件(使用Android的下载管理器),就会有一个广播接收器接收并处理文件以进行解压缩。压缩文件后,将保留另一个文件以供下载。代码是这样的:

public class DownloadService extends Service {

List<String> urlsToBeDownloaded;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   // set urlsToBeDownloaded
   registerReceiver(onComplete, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
   Utility.downloadFromUrl(urlsToBeDownloaded.get(0),this);
}

BroadcastReceiver onComplete = new BroadcastReceiver() {
    public void onReceive(Context ctxt, Intent intent) {
        new ProcessNext().execute(intent);
    }
};

  ProcessNext extends AsyncTask<Intent, Integer, Integer> {
    @Override
    protected Integer doInBackground(Intent... params) {
        return processNext(params[0]);
    }
 }

 protected int processNext(Intent intent) {
    Query query = new Query();
    ObjectOutputStream oos = null;
        Long dwnId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,
                0);
        query.setFilterById(dwnId);
        DownloadManager manager = (DownloadManager) (this)
                .getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor cursor = manager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor
                    .getColumnIndex(DownloadManager.COLUMN_STATUS));
            String title = cursor.getString(cursor
                    .getColumnIndex(DownloadManager.COLUMN_TITLE));
            File f1 = new File(Environment
                    .getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath()
                    + "/" + title);
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
                 Utility.extractFile(title);
                 urlsToBeDownloaded.remove(0);
                 if(urlsToBeDownloaded.size() != 0)
                     Utility.downloadFromUrl(urlsToBeDownloaded.get(0))
                 else
                     //show done message
            }
           }
          }
     }

我在这里尝试按顺序执行的操作意味着只有在下载和提取上一个文件时才会处理文件以供下载。

问题:

当我看到下载文件夹时,一次会下载多个文件。我无法理解多个文件的下载方式。有没有办法将其修复为顺序下载?

0 个答案:

没有答案