在android进行多线程操作,可以使用android.os.HandlerThread,android.os.Handler类来进行。

下面的例子是,界面上一个TextView控件,使用一个新线程在这个TextView上面显示数字,每隔1秒加1,按button后,停止更新计数。

package Test.wangfu;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TestActivity extends Activity {

/** Called when the activity is first created. */
private boolean isRuning=true;
private int timer=0;
private Handler hander;
private HandlerThread thread;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
final Button button = (Button) this.findViewById(R.id.callButton);
text = (TextView) this.findViewById(R.id.textLabel);
class mylistener implements OnClickListener {
public void onClick(View v) {
isRuning=false;
text.setText("结束");
}
}
button.setOnClickListener(new mylistener());

//多线程
thread=new HandlerThread("mytestthread");
thread.start();
hander=new Handler(thread.getLooper());

Runnable r=new Runnable(){

public void run() {
// TODO Auto-generated method stub
if(isRuning){

//使用runOnUiThread更新控件值,不使用的话将会出现:Only the original thread that created a //view hierarchy can touch its views.的错误。
TestActivity.this.runOnUiThread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
text.setText(String.valueOf(timer));
}});
timer++;
hander.postDelayed(this, 1000);
}
}
};
hander.postDelayed(r, 1000);
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter Number to Dial:" />

<Button
android:id="@+id/callButton"
android:layout_width="159dp"
android:layout_height="wrap_content"
android:text="停止" />

</LinearLayout>

更多相关文章

  1. Android语音声波控件 Android条形波控件
  2. Android(安卓)support library支持包常用控件介绍(一)
  3. Android(安卓)省市县 三级联动(android-wheel的使用)
  4. ArcGIS for Android地图控件的5大常见操作转
  5. ViewPager实现引导页
  6. Android(安卓)Flutter:Dart语言(布局篇)
  7. 语言转换的一些问题以及让dialog没有标题
  8. 底部导航栏中间凸出效果
  9. 关于更新UI

随机推荐

  1. GopherChina 2021 定了,干货满满的来了
  2. 山东潍坊某数据恢复公司客户服务器感染 .
  3. .[pbs@criptext.com].elder后缀的勒索病
  4. webpack 不同 sourcemap 含义?
  5. jira如何部署
  6. 【数据恢复案例】深圳某电子公司服务器感
  7. 感染.CC6H后缀勒索病毒导致深圳某公司金
  8. 甘肃某公司服务器感染.makop后缀勒索病毒
  9. 2021年.lockbit后缀勒索病毒卷土重来,如何
  10. 使用开源项目的风险