简体   繁体   中英

Update UI-Thread from a Android-AsyncTask in a while-loop

I am using a while-loop in an AsyncTask. The program is awaiting socket-request like

while(true) {
  in = readLine();
...
}

How I can update the main UI from this loop of the AsyncTask. Normally it's forbidden to update the main thread, and to do it in doPostExecute does not solve the problem, because then I have to leave the while-loop.

One way to accomplish this, could be to call publishProgress(object) somewhere in your loop. This, in turn, calls the method onProgressUpdate(Object[]) in which you can update views in the main thread.

In my example below, mTextView is a member variable of the class in which the AsyncTask resides. Eg

public class NewtworkActivity extends AppCompatActivity {
    private TextView mTextView;

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

        mTextView = (TextView) findViewById(R.id.text_view);
        ....
    }

    private class MySyncTask extends AsyncTask {
        ....
        @Override
        protected Object doInBackground(Object[] objects) {
            ....
            while (true) {
                while ((lineFromServer = mFromServer.readLine()) != null) {
                    Object object[] = { lineFromServer };
                    publishProgress(object);
                }
             }
        }

        ....

        @Override
        protected void onProgressUpdate(Object[] values) {
            super.onProgressUpdate(values);
            if (values.length > 0) {
                mTextView.append(values[0]+System.getProperty("line.separator"));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM