Timer主要用于创建每隔一段时间就执行的任务。
创建继承Task的任务类,也就是每段时间执行的任务。
private class MyTask extends TimerTask { @Override public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } } }
之后就可以使用了
Timer timer = new Timer(); timer.schedule(new MyTask(), 1, 2000);
Hanler机制:使用hanler.sendMessage(msg)传递Message参数 在新建Handler中的handleMessage( )
方法接受参数。根据msg.what进行操作判断,进行相应的操作。
整体代码:
package com.example.androidtest; 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.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { TextView show; @SuppressLint("HandlerLeak") Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case 1: show.setText("标题为:" + title); title ++; break; } super.handleMessage(msg); } }; int title = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (TextView)findViewById(R.id.show); Timer timer = new Timer(); timer.schedule(new MyTask(), 1, 2000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private class MyTask extends TimerTask { @Override public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } } }
时间: 2024-12-12 22:23:30