简体   繁体   English

从另一个线程访问 UI 线程的视图

[英]Accessing View of UI Thread from another Thread

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.我读到从 UI 线程创建的视图不能直接从另一个线程访问,而不使用 post() 方法利用 looper/Handler 或 RunonUI() 方法。 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.我尝试对此进行测试并创建了一个测试 class 如下,但我可以直接从新线程更改视图值。 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);
            }
        }
    }


}

You can user Handler, AsyncTask and very ease user runOnUiThread() I hope it's userful您可以使用 Handler、AsyncTask 和非常轻松的用户 runOnUiThread() 我希望它很有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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