下载管理器完成多次下载后如何执行任务

时间:2014-11-04 06:47:32

标签: java android broadcastreceiver android-download-manager

我需要在应用程序启动时下载多个图像。我能够正确下载图像,但我面临的问题是如何执行任务,如移动到另一个活动(显示图片的地方)或在这种情况下(用于测试目的)更改文本视图的文本一旦 ALL 下载完成。在我的代码中,即使一次下载完成,也会更改文本视图,这不是我想要的。我如何实现这一目标?

public class MainActivity extends ActionBarActivity {
TextView testtv;
String[] imagenames;
String BASEURL;
private long enqueue;
private DownloadManager dm = null;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BASEURL = getResources().getString(R.string.base_URL);
    imagenames = getResources().getStringArray(R.array.pic_name);
    testtv = (TextView) findViewById(R.id.testtv);
    File Path = getExternalFilesDir(null);
    File noMedia = new File(Path + "/.nomedia");
    if (!noMedia.exists()) {
        try {
            noMedia.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    Path.mkdirs();
    for (int index = 0; index < imagenames.length; index++) {
        File image = new File(Path + "/" + imagenames[index]);

        if (image.exists()) {
            testtv.setText("file exists");
        } else {
            Boolean result = isDownloadManagerAvailable(getApplicationContext());
            if (result) {
                downloadFile(imagenames[index]);
            }
        }

    }

}

@SuppressLint("NewApi")
public void downloadFile(String imagename) {
    // TODO Auto-generated method stub
    String DownloadUrl = BASEURL + imagename;
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(DownloadUrl));
    request.setDescription("P3 Resources"); // appears the same
                                            // in Notification
                                            // bar while
                                            // downloading
    request.setTitle("P3 Resources");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    }
    String fileName = DownloadUrl.substring(
            DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
    request.setDestinationInExternalFilesDir(getApplicationContext(), null,
            fileName);

    // get download service and enqueue file
    dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    enqueue = dm.enqueue(request);

}

public static boolean isDownloadManagerAvailable(Context context) {
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName("com.android.providers.downloads.ui",
                "com.android.providers.downloads.ui.DownloadList");
        List<ResolveInfo> list = context.getPackageManager()
                .queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    } catch (Exception e) {
        return false;
    }
}

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            Query query = new Query();
            query.setFilterById(enqueue);
            Cursor c = dm.query(query);
            if (c.moveToFirst()) {
                int columnIndex = c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c
                        .getInt(columnIndex)) {
                    testtv.setText("Download Complete");

                }
            }
        }
    }
};

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onResume() {
    super.onResume();

    registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}

2 个答案:

答案 0 :(得分:1)

您目前只存储从DL管理器返回的最后一个ID。将其更改为线程安全队列 - 如果我理解您的使用可以正确使用,则应该修复它。

public class MainActivity extends ActionBarActivity {
TextView testtv;
String[] imagenames;
String BASEURL;
private Queue<Long> enqueue = new ConcurrentLinkedQueue<>(); 
private DownloadManager dm = null;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BASEURL = getResources().getString(R.string.base_URL);
    imagenames = getResources().getStringArray(R.array.pic_name);
    testtv = (TextView) findViewById(R.id.testtv);
    File Path = getExternalFilesDir(null);
    File noMedia = new File(Path + "/.nomedia");
    if (!noMedia.exists()) {
        try {
            noMedia.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    Path.mkdirs();
    for (int index = 0; index < imagenames.length; index++) {
        File image = new File(Path + "/" + imagenames[index]);

        if (image.exists()) {
            testtv.setText("file exists");
        } else {
            Boolean result = isDownloadManagerAvailable(getApplicationContext());
            if (result) {
                downloadFile(imagenames[index]);
            }
        }

    }

}

@SuppressLint("NewApi")
public void downloadFile(String imagename) {
    // TODO Auto-generated method stub
    String DownloadUrl = BASEURL + imagename;
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(DownloadUrl));
    request.setDescription("P3 Resources"); // appears the same
                                            // in Notification
                                            // bar while
                                            // downloading
    request.setTitle("P3 Resources");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    }
    String fileName = DownloadUrl.substring(
            DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length());
    request.setDestinationInExternalFilesDir(getApplicationContext(), null,
            fileName);

    // get download service and enqueue file
    dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    enqueue.offer(dm.enqueue(request));

}

public static boolean isDownloadManagerAvailable(Context context) {
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName("com.android.providers.downloads.ui",
                "com.android.providers.downloads.ui.DownloadList");
        List<ResolveInfo> list = context.getPackageManager()
                .queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    } catch (Exception e) {
        return false;
    }
}

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            if (enqueue.contains(downloadId)) {
                enqueue.remove(downloadId);
            }

            if (!enqueue.isEmpty()) {
                return;
            }

            //not waiting on any more downloads
            testtv.setText("Downloads Complete");
        }
    }
};

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onResume() {
    super.onResume();

    registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}

答案 1 :(得分:0)

首先,我必须说听起来根本就不应该使用下载管理器。

如果你想下载图像并显示它们,你应该只使用HTTPUrlConnection或类似的方法并按照这种方式进行。

也就是说,有几种方法可以达到你想要的效果。

Java Futures是一种方法。 RxJava可能是个不错的选择。

哎呀,只需将预期结果添加到数组中,并在onReceive中迭代它就可以了。