0

如何排队下载大图?我用过Service。队列也是动态的。如果用户开始下载 3 张图片,我将启动下载 3 张图片的服务。但用户也可以添加更多图像以供下载,但我必须添加队列并一一下载所有图像。

我可以使用处理程序Service吗?我可以使用handler.sendMessage(msg1)handler.sendMessage(msg2)吗?我不知道处理程序中的方法handleMessage(msg)巧妙地维护队列。

和是msg1同时msg2处理还是在队列中处理?如果一一处理就解决了我的问题(意思msg2是完成后处理msg1)。

或者是否有任何可用的队列管理流程?

这是我想为下载图像和我想存储的下载图像ID创建队列,但如果有任何队列维护某些任务,那么它将会是一个很棒的智能队列。

在 Android 中排队下载文件并没有让我满意。

4

1 回答 1

0

处理程序本身管理消息队列

这可以在Service.

我做了示例..我将在队列中使用自定义流程...这里可供下载..

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Message msg = h.obtainMessage();
    msg.what = 0;
    msg.obj = "url1";
    h.sendMessage(msg);

    Message msg1 = h.obtainMessage();
    msg1.what = 1;
    msg1.obj = "url2";
    h.sendMessage(msg1);

    Message msg2 = h.obtainMessage();
    msg2.what = 2;
    msg2.obj = "url2";
    h.sendMessage(msg2);

    Message msg3 = h.obtainMessage();
    msg3.what = 3;
    msg3.obj = "url3";
    h.sendMessage(msg3);
}

Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        Log.e("", "handleMessage(msg) " + msg.what);
        download("" + System.currentTimeMillis(), "" + msg.obj);
        super.handleMessage(msg);
    }
};

private void download(String name, String link) {

    try {

        // Debug.e("", photo.imagename);
        URL url = new URL(link);
        HttpGet httpRequest = new HttpGet(url.toURI());

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
        InputStream input = bufHttpEntity.getContent();

        File outPutFile = new File(
                Environment.getExternalStorageDirectory(), name);
        OutputStream output = new FileOutputStream(outPutFile);

        try {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, bytesRead);
            }

        } finally {
            output.close();
            input.close();
        }

        // Toast.makeText(mContext, "Download completed",
        // Toast.LENGTH_SHORT).show();

        // incrementCounter(Constant.ACTION_DOWNLOADS, photo.iid);

    } catch (Exception e) {
        e.printStackTrace();
    }

 }
}

欢迎其他最佳实践...

于 2013-01-02T05:35:17.807 回答