Android Studio - поток пользовательского интерфейса не обновляется с помощью Asyn c Task - PullRequest
1 голос
/ 11 июля 2020

У меня следующая проблема: у меня есть мобильное приложение, которое при нажатии кнопки («yesbutton») извлекает данные с сервера в Asyn c Task (который отлично работает). Пока эта задача выполняется, я хочу, чтобы мое приложение отображало макет (framelayout), который я установил невидимым при создании и который содержит текстовое представление и круговую полосу выполнения. Поэтому я помещаю строку, в которой я установил ее видимой, в свой метод onPreExecute в моей задаче Asny c, потому что я читал, что этот метод будет выполняться в потоке пользовательского интерфейса.

Но этот макет кадра отображается только после моего весь код запущен, но не во время выполнения.

Вот мой код, я удалил из него кусок, в котором я не думаю, что проблема, чтобы сделать его более читаемым для вас.

public class KeepImageActivity extends AppCompatActivity {

    private static final int PORT_NO = 1234;
    private String pathname;
    private File imgFile;
    private Button yesbutton;
    private Button nobutton;
    private ImageView imageView;
    private FrameLayout frameLayout;


    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_keep_image);

        Intent receivedIntent = getIntent();
        pathname = receivedIntent.getStringExtra(CameraActivity.EXTRA_MESSAGE);
        imgFile = new File(pathname);

        imageView = findViewById(R.id.imageViewID);
        yesbutton = findViewById(R.id.yesbuttonID);
        nobutton = findViewById(R.id.discardbuttonID);

        nobutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDiscard(pathname);
            }
        });
        yesbutton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {
                onYes();
            }
        });

        frameLayout = findViewById(R.id.framelayout);
        frameLayout.setVisibility(View.GONE);
        showImage();
    }

    //method to show a picture in an ImageView
    private void showImage() {
        imgFile = new File(pathname);
        Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        imageView.setRotation(90);
        imageView.setImageBitmap(bitmap);
    }

    private void onDiscard(String pathname) {
        //....not relevant
}


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void onYes() {

        //doInBackground just fetches data and writes to jpg
        class ConnectTask extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... voids) {
                //doing stuff (connection to server and downloading image ("image_from_server"))
            }

            @Override
            //here my frameLayout is not being set to Visible, at least not DURING execution.
            protected void onPreExecute() {
                frameLayout.setVisibility(View.VISIBLE);

            }

            @Override
            protected void onPostExecute(Void aVoid) {

            }

            @Override
            protected void onProgressUpdate(Void... values) {
            }
        }



        ConnectTask connect =  new ConnectTask();
        Void[] param = null;

        //execute Async task
        connect.execute(param);


        //wait until picture on Phone
        File xaifile = new File(Environment.getExternalStorageDirectory() + "/image_from_server.jpg");
        while (true){
            if (xaifile.exists()){
                break;
            }
        }
        replacePicture(xaifile);
    }


    //here i replace the picture/bitmap in the ImageView with another one (that just came from server)
    private void replacePicture(File xaifile) {
        Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/image_from_server.jpg");
        imageView.setRotation(90);
        imageView.setImageBitmap(bitmap);

        //finished loading, I commented this line to see if my Layout would show afterwards. It does.
        //frameLayout.setVisibility(View.INVISIBLE);

        //delete both files, not needed anymore
        xaifile.delete();
        imgFile.delete();
    }

//AND IT SEEMS LIKE HERE IS THE MOMENT THAT THE UPDATE TO THE UI IS SHOWN. WHY??
}

1 Ответ

2 голосов
/ 11 июля 2020

Напишите эту часть:

//wait until picture on Phone
    File xaifile = new File(Environment.getExternalStorageDirectory() + "/image_from_server.jpg");
    while (true){
        if (xaifile.exists()){
            break;
        }
    }
    replacePicture(xaifile);

в onPostExecute

В настоящее время вы блокируете основной поток.

...