的Andr​​oid如何实现并行执行的AsyncTask [英] Android how to implement parallel execution for AsyncTask

查看:135
本文介绍了的Andr​​oid如何实现并行执行的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要允许多个的AsyncTask到在同一时间运行。 这是我的我的AsyncTask:

 私人无效callAPI(字符串USER_ID){
    新的AsyncTask<虚空,虚空,字符串>(){

            保护字符串doInBackground(空...参数){



                名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
                params.add(新BasicNameValuePair(user_ID的,USER_ID));

                返回api.post(,则params);


            } //结束doInBackground


            保护无效onPostExecute(字符串结果){
                Log.i(TAG +POST()=>中+导致);


            } //结束onPostExecute
        }。执行(); //结束的AsyncTask
      }
 

我看到,在<一个答案href="http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible">running-multiple-asynctasks但我不知道如何使用它。 我怎样才能实现下面的code我的AsyncTask内:

  @TargetApi(Build.VERSION_ codeS.HONEYCOMB)// API 11
无效startMyTask(AsyncTask的AsyncTask的){
    如果(Build.VERSION.SDK_INT&GT; = Build.VERSION_ codeS.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,则params);
    其他
        asyncTask.execute(PARAMS);
}
 

解决方案

 进口java.util.concurrent.BlockingQueue中;
进口java.util.concurrent.LinkedBlockingQueue中;
进口java.util.concurrent.ThreadFactory;
进口java.util.concurrent.ThreadPoolExecutor中;
进口java.util.concurrent.TimeUnit中;
进口java.util.concurrent.atomic.AtomicInteger中;

进口android.annotation.Sup pressLint;
进口android.os.AsyncTask;
进口android.os.Build;

/ **
 *为并发执行的AsyncTask任务的执行者
 *这需要所有的工作对理解device`s Android版本
 *兼执行你AsyncTasks任务
 * @author阿尔乔姆Zinnatullin(artem.zinnatullin@gmail.com)
 * @version 1.2
 * /
公共类AsyncTaskExecutor {

    私有静态最终诠释CORE_POOL_SIZE;
    私有静态最终诠释MAXIMUM_POOL_SIZE;
    私有静态最终诠释KEEP_ALIVE;
    私有静态最后的TimeUnit TIME_UNIT;

    私有静态最后的BlockingQueue&LT;可运行&GT; concurrentPoolWorkQueue;
    私有静态最后的ThreadFactory concurrentThreadFactory;
    私有静态最后的ThreadPoolExecutor concurrentExecutor;

    私人AsyncTaskExecutor(){}

    静态{
        CORE_POOL_SIZE = 5;
        MAXIMUM_POOL_SIZE = 128;
        KEEP_ALIVE = 1;
        TIME_UNIT = TimeUnit.SECONDS;

        concurrentPoolWorkQueue =新的LinkedBlockingQueue&LT;可运行&GT;(10);
        concurrentThreadFactory =新AsyncTaskThreadFactory();
        concurrentExecutor =新的ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                永葆,
                TIME_UNIT,
                concurrentPoolWorkQueue,
                concurrentThreadFactory
        );
    }

    / **
     *同时在任何Android版本执行的AsyncTask
     * @参数的任务来执行
     *参数PARAMS任务
     * @返回执行的AsyncTask
     * /
    @燮pressLint(NewApi)
    公共静态&LT; PARAMS,进展,结果&GT; AsyncTask的&LT; PARAMS,进展,结果&GT;
        executeConcurrently(AsyncTask的&LT; PARAMS,进展,结果&GT;的任务,参数... PARAMS){
        如果(Build.VERSION.SDK_INT&GT; = Build.VERSION_ codeS.HONEYCOMB){
            task.executeOnExecutor(concurrentExecutor,则params);
        } 其他 {
            task.execute(PARAMS);
        }

        返回任务;
    }

    / **
     *线程工厂AsyncTaskExecutor
     * @author阿尔乔姆Zinnatullin
     * /
    私有静态类AsyncTaskThreadFactory实现的ThreadFactory {
        私人最终的AtomicInteger计数=新的AtomicInteger(1);;

        @覆盖
        公共主题newThread(Runnable的R){
            返回新的线程(R的AsyncTask#+ count.getAndIncrement());
        }
    }
}
 

如果你想同时执行AsyncTask的使用这个类。发现这个类及其为我工作。

  AsyncTaskExecutor.executeConcurrently(新YourAsyncTask(),1);
 

的AsyncTask

 私有类YourAsyncTask扩展的AsyncTask&LT;整数,整数,字符串&GT; {
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            Toast.makeText(mContext,请wait..Fetching数据,
                    Toast.LENGTH_LONG).show();
        }

        @覆盖
        保护字符串doInBackground(整数... PARAMS){
            Log.e(传​​递价值,+参数[0]);
            字符串URI =htt​​p://abcd.com/ServiceTest.php?id=
                    +参数[0];
            Log.e(传​​递值,+ URI);
            返回SetServerString;
        }

        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(SetServerString);

    }
 

希望它可以帮助你!

I need to allow multiple AsyncTask to be running at the same time . This my my AsyncTask :

 private void callAPI(String user_id) {
    new AsyncTask<Void, Void, String>() {

            protected String doInBackground(Void... parameters) {



                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id",    user_id));

                return api.post("", params);


            }//end doInBackground


            protected void onPostExecute(String result) {
                Log.i(TAG + "POST() => " + result);


            }//end onPostExecute
        }.execute(); //end AsyncTask
      }

I saw an answer at running-multiple-asynctasks but I don't know how to use it . How can I implement the code below within my AsyncTask :

     @TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}

解决方案

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;

/**
 * An executor for concurrently executing AsyncTask tasks
 * It takes all work for understanding device`s Android version 
 * and executes your AsyncTasks tasks concurrently
 * @author Artem Zinnatullin (artem.zinnatullin@gmail.com)
 * @version 1.2
 */
public class AsyncTaskExecutor {

    private static final int CORE_POOL_SIZE;
    private static final int MAXIMUM_POOL_SIZE;
    private static final int KEEP_ALIVE;
    private static final TimeUnit TIME_UNIT;

    private static final BlockingQueue<Runnable> concurrentPoolWorkQueue;
    private static final ThreadFactory concurrentThreadFactory;
    private static final ThreadPoolExecutor concurrentExecutor;

    private AsyncTaskExecutor() {}

    static {
        CORE_POOL_SIZE    = 5;
        MAXIMUM_POOL_SIZE = 128;
        KEEP_ALIVE        = 1;
        TIME_UNIT         = TimeUnit.SECONDS;

        concurrentPoolWorkQueue = new LinkedBlockingQueue<Runnable>(10);
        concurrentThreadFactory = new AsyncTaskThreadFactory();
        concurrentExecutor      = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE,
                TIME_UNIT,
                concurrentPoolWorkQueue,
                concurrentThreadFactory
        );
    }

    /**
     * Concurrently executes AsyncTask on any Android version
     * @param task to execute
     * @param params for task
     * @return executing AsyncTask 
     */
    @SuppressLint("NewApi") 
    public static <Params, Progress, Result> AsyncTask<Params, Progress, Result> 
        executeConcurrently(AsyncTask<Params, Progress, Result> task, Params... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(concurrentExecutor, params);
        } else {
            task.execute(params);
        }

        return task;
    }

    /**
     * Thread factory for AsyncTaskExecutor
     * @author Artem Zinnatullin
     */
    private static class AsyncTaskThreadFactory implements ThreadFactory {
        private final AtomicInteger count = new AtomicInteger(1);;

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + count.getAndIncrement());
        }
    }
}

Use this class if you want to execute concurrently Asynctask. Found this class and its working for me.

AsyncTaskExecutor.executeConcurrently(new YourAsyncTask(),1);

Asynctask

private class YourAsyncTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(mContext, "Please wait..Fetching Data",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Integer... params) {
            Log.e("passing value",""+params[0]);
            String uri = "http://abcd.com/ServiceTest.php?id="
                    + params[0];
            Log.e("passing value",""+uri);
            return SetServerString;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(SetServerString);

    }

Hope it helps you!

这篇关于的Andr​​oid如何实现并行执行的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆