我有对象(不在ui线程上)需要将async任务作为内部方法运行,我想将ui线程传递给方法,然后在asynctask上实现ui线程 - 有没有办法这样做?
伪码:
public class EditDetails extends Activity{
MyObject obj = new obj;
obj.syncWithServer(EditDetails.this);
}
public class MyObject {
public void syncWithWerver(EditDetails parent){
final class GetUserHttpTask extends AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
@Override
protected String doInBackground(String... params) {
return "";
}
@Override
protected String onPostExecute(String result) {
//this doesn't run
}
}
}
}
注意:目前这不起作用,因为onPostExecute在doInBackground之后没有触发
修改
此代码是伪代码,实际问题仍在发生,我已将其列为http://pastebin.com/jW6JpUbg here ..基本上它在粘贴板上运行第72行后卡住,从不执行onPostExecute
答案 0 :(得分:2)
奇怪的是,onPostExecute
应为void
。我想知道你的代码是如何编译的,因为你改变了重写方法的返回类型?
更正onPostExecute
后,您可以按照以下步骤运行AsyncTask
:
final class GetUserHttpTask extends AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
@Override
protected String doInBackground(String... params) {
return "";
}
@Override
protected String onPostExecute(String result) {
// this will run
}
}
public void syncWithWerver(EditDetails parent){
AsyncTask task = new GetUserHttpTask();
task.execute();
}
答案 1 :(得分:1)
您是否尝试过像这样执行任务?
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
new GetUserHttpTask().execute();
}
});
我认为这应该有效..
<强>加了:强>
您的AsyncTask
实施应如下所示:
注意:阅读更新的评论
class GetUserHttpTask extends AsyncTask<String/* in parameter for doInBackground */, Boolean /* in parameter for onProgressUpdate */, String /* Out parameter and in parameter for onPostExecute method*/> {
@Override
protected String doInBackground(String... params) {
return "";
}
@Override
protected void onPostExecute(String result) {
// this doesn't run
}
@Override
protected void onProgressUpdate(Boolean... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}