我有一個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()
方法中,外部甚至是主Activity的「容器」,到publishProgress()
方法?我已閱讀此主題:Difficulty in changing the message of progress dialog in async task - 但它不是一個有效的幫助來源,因爲我的方法不包含在主類public class MainActivity extends Activity {}
中。
編輯#1 -
後的一些工作,我意識到,唯一的辦法就是傳遞給外部類referece的「主」線程,然後實現有特定的方法來發布進展情況。以這樣的方式:
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