public class MainActivity extends Activity {
      private TextView tv;
  private Button button;
  private Handler handler = new Handler();
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button)findViewById(R.id.buttonId);
    tv = (TextView)findViewById(R.id.textViewId);
    button.setOnClickListener(new MyButton());
  }
  class MyButton implements OnClickListener {
    @Override
    public void onClick(View v) {
      Thread t = new MyThread();
      t.start();
    }
  }
  class MyThread extends Thread {
    @Override
    public void run() {
      Runnable runnable = new Runnable() {
        @Override
        public void run() {
          //比如这里从网络中获取到了数据吗,在这里直接可以更新主线程中的数据
          String currentString = Thread.currentThread().getName();
          System.out.println("当前线程的名称为:"+currentString);
          tv.setText(currentString);
        }
      };
      handler.post(runnable);
    }
  }
}

 

post机制将runnable对象运行在主线程中的

相关文章:

  • 2021-08-06
  • 2021-06-25
  • 2021-08-02
  • 2022-12-23
  • 2021-05-03
猜你喜欢
  • 2022-12-23
  • 2021-11-21
  • 2021-12-03
  • 2021-05-02
  • 2021-04-23
相关资源
相似解决方案