Accessing View of UI Thread from another Thread

206 views Asked by At

I read that views created from UI thread can't be accessed from another thread directly without using post() method utilizing looper/Handler or RunonUI() method. This is for security reasons. I tried to test this and created a test class as below but I am able to change values of views from a new thread directly. Is there any gap in my understanding or doing something wrong ?

import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class RemoteBoundActivity extends AppCompatActivity {

    private static final String TAG = "RemoteBoundActivity";
    TextView numbertTextView = null;
    Button button = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_bound);
        numbertTextView = (TextView) findViewById(R.id.numbertTextView);
        button = findViewById(R.id.startTask);
    }

    public void startTask(View view) {
        new WorkerThread().start();
    }

    public void stopTask(View view) {
        Log.i(TAG, "stopTask executed");
        Toast.makeText(getBaseContext(), "Task Stopped", Toast.LENGTH_SHORT).show();
    }

    private class WorkerThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                SystemClock.sleep(1000);
                numbertTextView.setText(i+"%");
                button.setText(i+"%");
                Log.i(TAG, "startTask: Thread ID : "+Thread.currentThread().getId()+" value :"+i);
            }
        }
    }


}
1

There are 1 answers

1
LuongXuanNam On

You can user Handler, AsyncTask and very ease user runOnUiThread() I hope it's userful