0

AsyncTask を使用して文字列をダウンロードし、文字列を返そうとしています。時間がかかるかもしれないので AsyncTask を使いたいです。

1 つの問題は、インターネット上のどこにも、AsyncTask が何らかの種類の値を返す例が見つからないことです。そこで、Commonsware book の例を使用して値を返すように変更し、次のように値を取得しました。

String mystr = new AddStringTask().execute().get();

これは機能しますが、このコード行は戻り値を待っているため、同期しているようです。AddStringTask の結果でイベント トリガーを発生させる何らかの方法が必要です。

それはどのように行われますか?ありがとう、ゲイリー

4

2 に答える 2

2

An AsyncTask cannot return a value, because to get the returned value you would have to wait before the task is finished. That would make the AsyncTask meaningless.

Instead, you should move your code in onPostExecute() (which runs on the UI thread, if this is what you worry about). This is where you handle the value returned by doInBackground() and typically update the UI or show an error message.

于 2012-09-17T22:25:08.050 に答える
0

また、より一般的な AsyncTask を実装したい場合は、次のようなものを実装して、アクティビティ内のコードを区分化できます。

@Override
protected void onPostExecute(Bitmap r){
    if (r != null) {
        processListeners(r);
    }
}

protected void processListeners(Object data) {
    for (final AsyncTaskDone l : listeners) l.finished(data);
}

public void addAsyncTaskListener (final AsyncTaskDone l){
    listeners.add(l);
}

AsyncTaskListener は、onClickListener と同じ方法でアクティビティに実装された、finished という 1 つの関数を含むインターフェイスです。

于 2012-09-17T22:34:02.253 に答える