各种线程总结

本文介绍了在Android应用中如何正确地从后台线程更新用户界面的方法。包括使用runOnUiThread、View.post、Handler发送消息以及AsyncTask等不同方式来实现长时间运行操作后的UI更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.public void onClick(View v) {
    Thread t = new Thread(){
    public void run(){
 // Long time comsuming operation
   }
   };
   t.start();
}
public void onClick(View v) {
 Thread t = new Thread(){
  public void run(){
   // Long time consuming operation
   _activity.runOnUiThread(new Runnable() {

    @Override
    public void run() {
     _activity.setStatus("Long Operation Completed");

    }
   });
  }
 };
 t.start();
}
2.

public void onClick(View v) {
 // TODO Auto-generated method stub
 Thread t = new Thread(){
  @Override
  public void run() {
   // Long time consuming operation
   status.post(new Runnable() {

    @Override
    public void run() {
     status.setText("Long Operstion Completed");

    }
   });
  }
 };
 t.start();
}
3.

public void onClick(View v) {
 // TODO Auto-generated method stub
 Thread t = new Thread(){
  @Override
  public void run() {
   // Long time consuming operation
   status.postDelayed(new Runnable() {

    @Override
    public void run() {
     status.setText("Long Operstion Completed");

    }
   }, 1000);
  }
 };
 t.start();
}

4.

private Handler handler = new Handler() {
@Override
 public void handleMessage(Message msg) {
  // Code to process the response and update UI.
 }
};

public void onClick(View v) {
 Thread t = new Thread(){
  public void run(){
   // Long time comsuming operation
   Message myMessage=new Message();
   Bundle resBundle = new Bundle();
   resBundle.putString("status", "SUCCESS");
   myMessage.obj=resBundle;
   handler.sendMessage(myMessage);
  }
 };
 t.start();
}

5.

public class LongTimeConsumingOperation extends AsyncTask<String, Void, String> {

 @Override
 protected String doInBackground(String... params) {
  // perform Long time consuming operation
  return null;
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
  */
 @Override
 protected void onPostExecute(String result) {
  // TODO Auto-generated method stub
  super.onPostExecute(result);
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onPreExecute()
  */
 @Override
 protected void onPreExecute() {
  // TODO Auto-generated method stub
  super.onPreExecute();
 }

 /* (non-Javadoc)
  * @see android.os.AsyncTask#onProgressUpdate(Progress[])
  */
 @Override
 protected void onProgressUpdate(Void... values) {
  // TODO Auto-generated method stub
  super.onProgressUpdate(values);
 }

}

public void onClick(View v) {
new LongTimeConsumingOperation().execute("");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值