禁止使用的AsyncTask的,使用自定义的AsyncTask [英] Disable use of AsyncTask, using custom AsyncTask

查看:183
本文介绍了禁止使用的AsyncTask的,使用自定义的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实施的AsyncTask ,允许多个的AsyncTask s到并行运行:

I have the following implementation of AsyncTask, allowing multiple AsyncTasks to run concurrently:

public abstract class MyAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    public AsyncTask<Params, Progress, Result> executeCompat(Params... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            return executeOnExecutor(THREAD_POOL_EXECUTOR, params);
        } else {
            return execute(params);
        }
    }
}

现在,以避免混乱和意外使用正常的的AsyncTask ,我想阻止我的code访问:

Now to avoid confusion and accidental use of the normal AsyncTask, I would like to block access from my code to:


  • 的AsyncTask 类,只有 MyAsyncTask 应该被使用。

  • 的execute() MyAsyncTask 功能。

  • The AsyncTask class, only MyAsyncTask should be used.
  • The execute() function in MyAsyncTask.

是否有可能做到这一点?

Is it possible to do this?

推荐答案

我这样的想法是有点不同。相反延长了的AsyncTask 类,您可以创建需要作为的AsyncTask 要使用参数的方法。下面是一个例子:

My idea of doing this would be a bit different. Instead of extending the AsyncTask class, you can create a method that takes as a parameter the AsyncTask you want to use. Here is an example:

public void executeAsyncTask(AsyncTask asyncTask) {

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        asyncTask.executeOnExecutor(THREAD_POOL_EXECUTOR, params);
    } else {
        asyncTask.execute(params);
    }
}

有了这个,你只需要实例化要使用AsyncTask的,不用担心你所提到的,因为你会被延长的问题 Android的 的AsyncTask已经重写了 类执行方法,你想要的方式。因此,可以说,你已经定义了一个的AsyncTask 名为 customAsyncTask ,执行它,你只需要调用 executeAsyncTask(新customAsyncTask(your_params)); 您可以定义在静态类上述方法(制作方法也静态)更容易获得。

With this you just need to instantiate the AsyncTask you want to use without worrying about the problems you mentioned since you will be extending the Android's AsyncTask class having overriden the execute method the way you want. So lets say that you have defined an AsyncTask named customAsyncTask, to execute it you just call executeAsyncTask(new customAsyncTask(your_params)); You can define the above method in a static class (making the method also static) for easier access.

希望有所帮助:)

这篇关于禁止使用的AsyncTask的,使用自定义的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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