Android异步更新UI的方式之使用AsyncTask异步任务

由于性能要求,android要求只能在UI线程中更新UI,要想在其他线程中更新UI,给大家介绍一种方式:使用AsyncTask异步任务。

 

下面用这种方式更新一个TextView:

注:更新UI的操作只能在onPostExecute(String result)方法中。


package com.example.runonuithreadtest;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
new Yibu().execute();
}
class Yibu extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText("更新后的TextView");
}
}
}

 

当然对APP的性能测试,我比较常用的是这个平台:www.ineice.com

posted @ 2015-09-16 09:38  说走咱就走  阅读(318)  评论(0)    收藏  举报