Ion*_*gru 9 android android-asynctask
我正试图从另一个AsyncTask的 -method 开始一个AsyncTask ...... doInBackground()
这甚至可能吗?如果是,我怎样才能实现这一目标?
后期编辑:
我的想法是,我启动了一个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);
}
Run Code Online (Sandbox Code Playgroud)
这是从doInBackground()方法中已经启动的AsyncTask开始的...
我知道我可以在AsyncTask中添加方法,只需在doInBackground()方法中调用它们,但我需要在其他地方使用它们,我从onPostExecute启动这些AsyncTasks ...
如果你们认为有一个简单的解决办法,这不会影响我的表现,那将是很好的......如果不是,我将制作一些静态方法,我将在我需要的所有AsyncTasks中调用(但是这个将要求我修改我的很多代码)
waq*_*lam 15
AsyncTasks应该从主(UI)线程运行.您不应该从doInBackground运行另一个AsyncTask,因为此方法在非UI线程上执行.
在你的情况下,我可以建议你两件事:
Lan*_*tel 11
根据下面的帖子,你可以做Activity.runOnUiThread()在主线程上运行一个Runnable(来自另一个线程).
理论上你可以做到这一点:
顾名思义,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, String>() {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}).execute();
}
});
return null;
}
}).execute();
Run Code Online (Sandbox Code Playgroud)
这个嵌套的例子不是在生产中使用的好样式,因为(恕我直言)它接近不可读.
补充说明:
Activity.runOnUiThread(Runnable)不是静态的!这就是为什么我的例子使用ParentActivity(.this).runOnUiThread(Runnable).
小智 6
你不能这样做,doInBackground() 但你可以从onProgressUpdate()例如因为它在UI线程上运行.请记住,3.0之后它们将被放在同一队列中并且不会并行运行,请参阅executeOnExecutor