繁体   English   中英

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

[英]How to perform a task once download manger has completed multiple downloads

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

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));
}
}

您目前仅存储从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));
}
}

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

如果要下载图像并显示它们,很可能只应使用HTTPUrlConnection或类似的方法即可。

就是说,有几种方法可以实现您想要的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM