Android定时器和线程实现

在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" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="second"
        android:onClick="btn_second"/>

</LinearLayout>

MainActivity.java

package com.threaddemo;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

//定时器处理发送数据
public class MainActivity extends Activity
{
	//宏定义,表示是什么消息
	public static final int REFRESH = 0x01;
	//用来显示变化的值
	private int nValue = 0;
	//用来显示值得控件
	public TextView textView;
	
	//定时器设置
	Timer timer = new Timer();
	TimerTask task = new TimerTask()
	{
		@Override
		public void run()
		{
			nValue++;
			Message message = new Message();
			message.what = REFRESH;
			mhandler.sendMessage(message);
		}
	};
	
	//处理消息
	@SuppressLint("HandlerLeak")
	public Handler mhandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case REFRESH:
				RefreshData();
				break;
			default:
				break;
			}
		}
	};
	
	public void RefreshData()
	{
		textView.setText(String.valueOf(nValue));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textView = (TextView)findViewById(R.id.tv);
		
		nValue = 0;
		//开启定时器
		timer.schedule(task,1000,1000);
	}
	
	//跳转到下一个界面
	public void btn_second(View view)
	{
		Intent intent = new Intent(MainActivity.this,SecondActivity.class);
		startActivity(intent);
	}
	
	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		
		timer.cancel();
		timer.purge();
	}
}


效果如图

Android定时器和线程实现_第1张图片 Android定时器和线程实现_第2张图片


然后,实现线程操作

second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="ok"
        android:onClick="btn_ok"/>

</LinearLayout>

SecondActivity.java

package com.threaddemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;

//线程发送数据
public class SecondActivity extends Activity
{
	//宏定义,表示是什么消息
	public static final int REFRESH = 0x01;
	//用来显示变化的值
	private int nValue = 0;
	//用来显示值得控件
	public TextView textView;
	//线程
	private Thread mThread;
	//控制线程运行
	private boolean bIsRunning = false;
	
	//线程发送数据
	Runnable runnable = new Runnable() 
	{
        // 重写run()方法,此方法在新的线程中运行
        @Override
        public void run() 
        {
        	while (bIsRunning)
			{
        		Message message = new Message();
    			message.what = REFRESH;
    			message.arg1 = nValue;//发送消息时将值作为参数同时传递
    			mhandler.sendMessage(message);
    			
    			nValue++;
    			SystemClock.sleep(1000);//1000ms的延时
			}
        }
    };
    
    //处理消息
    @SuppressLint("HandlerLeak")
	public Handler mhandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case REFRESH:
				RefreshData(msg.arg1);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
    
    public void RefreshData(int value)
	{
		textView.setText(String.valueOf(value));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.second);
		
		textView = (TextView)findViewById(R.id.tv);
		
		nValue = 0;
		bIsRunning = true;
		//开启线程
		mThread = new Thread(runnable);
		mThread.start();
	}
	
	public void btn_ok(View view)
	{
		SecondActivity.this.finish();
	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		
		bIsRunning = false;
		mThread.interrupt();
	}
}

效果如图

Android定时器和线程实现_第3张图片 Android定时器和线程实现_第4张图片


源码下载


你可能感兴趣的:(线程,android,定时器,实现)