我有一个异步任务,doInBackground()
方法如下:
protected String doInBackground(String... params) {
MyClass session = new MyClass("email", "password");
return session.isAuthorized();
}
While 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 changed 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
. 如何在外部类中编写一个通用的绝对方法,我可以在多个特定的 AsyncThread 中使用它?
--> LOGs IN THE LOGIN THREAD 1
/
EXTERNAL CLASS ---> LOGs IN THE LOGIN THREAD 2
\
--> LOGs IN THE LOGIN THREAD 3