从AsyncTask调用不同的回调onPostExecute() [英] Call different callback from AsyncTask onPostExecute()

查看:46
本文介绍了从AsyncTask调用不同的回调onPostExecute()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的类实现了一个内部AsyncTask,它可以从服务器查询初始设置数据并将其存储到设备缓存中.设置数据分为2个JSON文件.读取/缓存第一个JSON,如果满足某些条件,则将下载第二个JSON文件并将其存储到缓存中.我想从两个操作中使用相同的AsyncTask.

I have implemented an internal AsyncTask for my class that does initial setup data query from server and stores into device cache. The setup data in split between 2 JSON files. The first JSON is read/cached and if certain conditions are on then second JSON file will be downloaded and stored into cache. I want to use same AsyncTask from both operations.

在doInBackground()中,我执行与JSON类型无关的JSON下载操作.但是在onPostExecute()中,我想根据其第一个JSON文件还是第二个JSON文件调用不同的回调,因为它们需要不同的处理.有可能吗?

In doInBackground(), I perform JSON download operation independent of JSON type. But in onPostExecute() I want to call different callbacks depending if its 1st JSON file or second, since they require different handling. Is that possible?

请注意,我不想使用布尔值,枚举来确定要调用的回调,因为将来我将要处理更多文件.从我的调用类中,我想设置回调,其余部分应自动发生.

Pls note I do not want to use booleans, enum to decide which callback to call as in future I will have more files to process. From my calling class I want to set the callback and rest should happen automatically.

推荐答案

以下实现应该可以解决您的问题:

Below implementation should solve your problem:

private class MyCustomAsyncTask extends AsyncTask<Void, Void, Void>{

        private boolean mShouldCallMethod1;

        public MyCustomAsyncTask(boolean shouldCallMethod1){
            mShouldCallMethod1 = shouldCallMethod1;
        }

        @Override
        protected Void doInBackground(Void... params) {
            //code goes here..
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if(mShouldCallMethod1){
                method1();
            }else{
                method2();  
            }
        }

    }

即,有一个自定义的AsyncTask作为内部类.

i.e have a customized AsyncTask as innerclass.

这篇关于从AsyncTask调用不同的回调onPostExecute()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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