android – 从另一个AsyncTask doInBackground()启动AsyncTask

我正在尝试从另一个AsyncTask的doInBackground() – 方法启动一个AsyncTask …

这有可能吗?如果是,我怎样才能做到这一点?

后期编辑:

我的想法是,我启动了一个asynctask,它将从Tweeter获取状态……一切正常,直到这里……但是当我遇到一些特定的推文时,我需要用我服务器上的一些信息修改它们,在这里我将创建另一个网络操作,因为我需要等到我从服务器获取信息后才会这样做:

GetContent getContentServiceAsyncTask = new GetContent(context);
try {
    tweetText = Uri.decode(getContentServiceAsyncTask.execute(
            URL_GET_CONTENT,jsonRequest).get());
} catch (InterruptedException e) {
    Log.e(TAG_DEBUG,"InterruptedException: ",e);
} catch (ExecutionException e) {
    Log.e(TAG_DEBUG,"ExecutionException: ",e);
}

这是从doInBackground()方法中已经启动的AsyncTask开始的……

我知道我可以在AsyncTask中添加方法,只需在doInBackground()方法调用它们,但我需要在其他地方使用它们,我从onPostExecute启动这些AsyncTasks …

如果你们认为有一个简单的解决办法,这不会影响我的表现,那将是很好的……如果不是,我将制作一些静态方法,我会在我需要的所有AsyncTasks中调用(但是这个将要求我修改我的很多代码)

解决方法

根据下面的帖子,你可以做Activity.runOnUiThread()在main-Thread上运行Runnable(来自另一个线程).

> Running code in main thread from another thread

理论上你可以做到这一点:

>运行异步任务
>在AsyncTask中执行Activity.runOnUiThread(Runnable)并从此runnable内部启动一个新的AsyncTask

顾名思义,Activity.runOnUiThread()在主线程上执行runnable

但它有点hacky.

代码看起来应该是这样的:(没有测试)

// first task
    (new AsyncTask<String,String,String>() {

        @Override
        protected String doInBackground(String... params) {
            ParentActitity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    //second async stared within a asynctask but on the main thread
                    (new AsyncTask<String,String>() {

                        @Override
                        protected String doInBackground(String... params) {
                            // Todo Auto-generated method stub
                            return null;
                        }

                    }).execute();

                }
            });
            return null;
        }

    }).execute();

这个嵌套的例子不是在生产中使用的好样式,因为(恕我直言)它接近不可读.

补充说明:

Activity.runOnUiThread(Runnable)不是静态的!这就是为什么我的例子使用ParentActivity(.this).runOnUiThread(Runnable).

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...