1

我编写了一个 Bolts 任务实现来获取一个 url:

public class UrlFetcher {

    private static final String LOG_TAG = "UrlFetcher";

    public static Task<byte[]> getUrl(String url) {
        final TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<>();
        try {
            tcs.setResult(downloadUrl(url));
        } catch (IOException e) {
            tcs.setError(e);
        }
        return tcs.getTask();
    }


    private static byte[] downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(LOG_TAG, "The response is: " + response);
            is = conn.getInputStream();

            byte[] bytes = IOUtils.toByteArray(is);
            return bytes;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

}

这是要运行的第一个任务。如何在后台执行程序上运行它?

似乎只有在继续另一个任务时才能指定执行者。

4

1 回答 1

3

您不需要使用 TaskCompletionSource,而是使用 Task.callInBackground:

public static Task<byte[]> getUrl(final String url) {
    return Task.callInBackground(new Callable<byte[]> {
        public byte[] call() {
            return downloadUrl(url);
        }
    });
}
于 2016-05-02T02:53:49.087 回答