LINUX.ORG.RU
решено ФорумMobile

AsyncTask and global variable

 , , , ,


0

1

Подскажите, почему такой код не работает?

package com.example.myapplication;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    static boolean performed = false;

    public class MyAsyncTask0 extends AsyncTask<String, Void, String> {

        public int v0 = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected synchronized String doInBackground(String... params) {
            Log.d("",Integer.toString(v0));
            return "";
        }

        @Override
        protected synchronized void onPostExecute(String result) {
            if (v0 == 1) performed = true;
        }
    }

    public class MyAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected synchronized String doInBackground(String... params) {
            return "";
        }

        @Override
        protected synchronized void onPostExecute(String result) {
            for (int i = 0; (i < 6) && (!performed); i++) {
                SystemClock.sleep(800);
                if (!performed) {
                    MainActivity.MyAsyncTask0 task0 = new MainActivity.MyAsyncTask0();
                    task0.v0 = i+1;
                    task0.execute();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MainActivity.MyAsyncTask task = new MainActivity.MyAsyncTask();
        task.execute();
    }
}

По задумке, первая задача ставит performed = true, и остальные просто не запускаются.

В реальности:

Capturing and displaying logcat messages from application. This behavior can be disabled in the «Logcat output» section of the «Debugger» settings page.
D/: 1
D/: 2
D/: 3
D/: 4
D/: 5
D/: 6