【发布时间】:2013-04-04 23:29:58
【问题描述】:
我有一个带有 doInBackground() 方法的异步任务,如下所示:
protected String doInBackground(String... params) {
MyClass session = new MyClass("email", "password");
return session.isAuthorized();
}
而MyClass,它在一个完全不同的包中,是这样的:
private class MyClass {
// fields, constructors, etc
public Boolean isAuthorized() {
// some stuff
log("Action 1...");
// some stuff
log("Action 2...");
// some other stuff
return result;
}
public static void log(String str) {
// HERE I would like to publish progress in the Async Task
// but, until now, it's kinda like:
System.out.println(str);
}
}
问题是:如何将log() 方法中的日志描述传递给publishProgress() 方法?我已经阅读了这个帖子:Difficulty in changing the message of progress dialog in async task - 但它不是有效的帮助来源,因为我的方法不包含在主类 public class MainActivity extends Activity {} 中。
编辑 #1 -
经过一些工作,我意识到唯一的方法是向外部类传递对“主”线程的引用,然后在那里实现一个特定的方法来发布进度。以这样的方式:
public void log(String str) {
if (mThreadReference==null) {
System.out.println(str);
} else {
mThreadReference.doProgress();
}
}
而mThreadReference 指向这个AsyncTask:
private class MyClassTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... params) {
// constructs MyClass instance with a reference and run main method
(new MyClass("email", "password", this)).isAuthorized();
}
public void doProgress(String str) {
publishProgress(str);
}
@Override
protected void onProgressUpdate(String... values) {
// some stuff
}
@Override
protected void onPostExecute(String result) {
}
}
但是,显然,Eclipse 是在警告我:The method publishProgress() is undefined for the type Activity。如何在外部类中编写general和absolute方法,以便在多个特定AsyncThread中使用?
--> LOGs IN THE LOGIN THREAD 1
/
EXTERNAL CLASS ---> LOGs IN THE LOGIN THREAD 2
\
--> LOGs IN THE LOGIN THREAD 3
【问题讨论】: