如何使用 ThreadPoolExecutor 调用 webservice

How to call webservice using ThreadPoolExecutor

我想在 android 应用程序中使用 ThreadPoolExecutor 调用网络服务,而不是 AsyncTask。 Webservice调用应该是并行和队列的。怎么做。

  1. 首先创建一个ThreadPoolExecutor实例:

    ExecutorService executor = Executors.newFixedThreadPool(<number of threads you needs inside pool>);

  2. 然后在 Runnable 方法中添加 api 调用:

    executor.execute(新的Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
    
        }
    });
    

更多详情:http://developer.android.com/reference/java/util/concurrent/ExecutorService.html

创建ThreadPoolExecutor的方法有很多种。最简单的是在 Executors 中创建使用预定义的执行程序。在它周围添加一个包装器以执行您的查询。

总的来说这是一个复杂的任务,因为你应该正确管理任务(取消,重新查询,...)。

请参阅下面的简单示例

public class RequestExecutor {

    private static final int POOL_SIZE = 2;

    private final ExecutorService mExecutorService;
    private final Handler mUiHandler;

    public RequestExecutor(Handler uiHandler) {
        mExecutorService = Executors.newFixedThreadPool(POOL_SIZE);
        mUiHandler = uiHandler;
    }

    public <E> void execute(final IRequest<E> request, final ResultListener<E> listener) {
        // manage future entry later, if need
        Future future = mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request requestHttp = new Request.Builder().url(request.getUrl()).build();

                try {
                    Response response = client.newCall(requestHttp).execute();
                    String responseString = response.body().string();
                    E resp = request.parse(responseString);
                    notifySuccess(listener, resp);
                } catch (Throwable e) {
                    notifyFailure(listener, e);
                    e.printStackTrace();
                }
            }
        });
    }

    protected void notifyFailure(final ResultListener<?> listener, Throwable e) {
        // handle exceptions here
        final int errorCode = 401;
        mUiHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onError(errorCode);
            }
        });
    }

    protected <E> void notifySuccess(final ResultListener<E> listener, final E resp) {
        mUiHandler.post(new Runnable() {
            @Override
            public void run() {
                listener.onSuccess(resp);
            }
        });
    }

    public interface IRequest<E> {
        String getUrl();

        E parse(String resp);
    }

    public interface ResultListener<E> {
        void onSuccess(E result);

        void onError(int errorCode);
    }
}