1

I am coding an app that give me some problems. I have an activity A with a button. When the user presses the button, it retrieves data from the Internet using an AsyncTask class, and when the data is retrieved, the AsyncTask class calls a method declared in activity A that starts a new activity B.

But this has a problem I don't know how to fix. If the user presses the button twice (or more than once), the data is retrieved two times and activity B is launched twice. So, once I am in activity B, when I press the back button that instance of Activity B is destroyed but I'm still in the activity B (because it was launched twice).

Some code from the AsyncTask class which download the data:

@Override
protected String doInBackground(String... urls) {
    try {
        String data = downloadUrl(urls[0]);
        return downloadUrl(urls[0]);
    } catch (IOException e) {
        return m_errorCODE;
    }
}

@Override
protected void onPostExecute(String result) {
    ((MainActivity) mParentActivity).displayInfo(result);
}

Method displayInfo() from MainActivity which launches the activity B:

public void displayInfo(String result) {
        int duration = Toast.LENGTH_LONG;
        Toast toast = null;
        setSupportProgressBarIndeterminateVisibility(false);
        if (result == "404 ERROR") {
            toast = Toast.makeText(getBaseContext(), R.string.error_file_not_found, duration);
            toast.show();
        } else if (result == "CONNECTION_ERROR") {
            toast = Toast.makeText(getBaseContext(), R.string.error_connection, duration);
            toast.show();
        } else {

            Intent intent = new Intent(this, DisplayInfo.class);
            m_data = result;
            intent.putExtra(DOWNLOADED_DATA, m_data);
            intent.putExtra(FORMAT_OK, Boolean.toString(m_formatOK));
            intent.putExtra(URL_FILE, urlFile);
            startActivity(intent);
        }
    }

So I have three problems:

  1. How can I download the data only once?
  2. How can I open activity B only once?
  3. How can I know in my Activity A is still alive when it executes onPostExecute()?

To solve #2 I tried using intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) before starting activity B. It opens only one activity B, but if I press back, activity A starts again another instance of activity B.

Do I need to paste more code? Thanks in advance.

4

3 に答える 3

0

#1 と #2 では、ボタンがクリックされた後に設定されるインスタンス変数をアクティビティで使用できます。ボタンの onClick() メソッドで、この変数をチェックして、AsyncTask を開始する必要があるかどうか、または既に開始されているかどうかを確認できます。

#3 では、mParentActivity が null でないかどうかをテストできますか? 私はそれについて確信が持てません。

于 2012-07-05T21:31:26.570 に答える
0

AsychTasks は、一度だけ実行される一種のスレッドです。http://developer.android.com/reference/android/os/AsyncTask.html

于 2012-07-05T21:32:56.733 に答える
0

代わりにProgressDialogクラスを使用してこれを行います。これを AsyncTask と組み合わせて使用​​する方法の例が Web 上に多数あります。

于 2012-07-05T21:34:51.120 に答える