android多线程--计时案例

在android应用开发中,多线程很常见,而且很java中的多线程有些不同。在android多线程中,主线程负责管理其他子线程,必须明确主线程和子线程的职责,否则统会抛出异常“Only the original thread that created a view hierarchy can touch its views”。这里我们可以用消息(Message)或消息队列(MessageQueue)解决。

Android线程涉及的技术有:Handler;Message;MessageQueue;Looper;HandlerThread。

这里的android编写风格虽然违背了java变成规范,但是在实际android开发应用中很常见。


程序运行结果:

下面看代码:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="关闭线程"
        android:onClick="closeThreadButton" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/timerView" />

</LinearLayout>

MainActivity.java

package org.mtn.threaddemo;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FinalActivity
{
	@ViewInject(id = R.id.timerView)
	TextView timerView;

	private boolean isRunning = true;
	private int timer = 0;
	
	private Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(0 == msg.what) timerView.setText("运行了" + msg.obj + "秒");
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while(isRunning)
				{
					try
					{
						Thread.currentThread().sleep(1000);
						timer ++;
						Message msg = new Message();
						msg.obj = timer;
						msg.what = 0;
						handler.sendMessage(msg);
						Toast.makeText(getApplicationContext(), "运行了" + timer + "秒", 1).show();
					} catch (Exception e)
					{
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public void closeThreadButton(View v)
	{
		isRunning = false;
	}
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值