我读到从 UI 线程创建的视图不能直接从另一个线程访问,而不使用 post() 方法利用 looper/Handler 或 RunonUI() 方法。这是出于安全原因。我尝试对此进行测试并创建了一个如下所示的测试类,但我可以直接从新线程更改视图的值。我的理解是否有任何差距或做错了什么?
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);
}
}
}
}