如何使用ThreadPoolExecutor调用webservice

时间:2015-08-14 08:11:53

标签: java android threadpoolexecutor

我想在Android应用程序中使用 ThreadPoolExecutor 而不是 AsyncTask 来调用web服务。 Webservice调用应该是并行和队列。怎么做。

2 个答案:

答案 0 :(得分:2)

有很多方法可以创建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);
    }
}

答案 1 :(得分:1)

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

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

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

    executor.execute(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
    
        }
    });
    
  3. 详细信息:http://developer.android.com/reference/java/util/concurrent/ExecutorService.html