Android Timer编写方式深解
- 许多编程人员都会认为,Android Timer的实现方法比较简单,其实真正的草率做起来并非如此。我们在这里就为大家介绍一下这方面的相关知识。
Android手机操作系统是一款基于Linux平台的开源手机操作系统。对于编程人员来说,修改这一操作系统的方法应该很容易就可以掌握。不过中间还是有许多细节需要我们注意。比如写惯java的人可能会认为Android Timer的使用应该如下:
程序功能很简单:10秒后,SetTitle为“hear me?”,然后,实际上这样做是不行的,这跟Android的线程安全有关!
Java代码
- package com.ray.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class JavaTimer extends Activity {
- Timer timer = new Timer();
- TimerTask task = new TimerTask(){
- public void run() {
- setTitle("hear me?");
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
- package com.ray.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class JavaTimer extends Activity {
- Timer timer = new Timer();
- TimerTask task = new TimerTask(){
- public void run() {
- setTitle("hear me?");
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
但实际上的用法应该通过配合Handler来实现Android Timer功能的!
Java代码
- package com.ray.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- public class TestTimer extends Activity {
- Timer timer = new Timer();
- Handler handler = new Handler(){
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- setTitle("hear me?");
- break;
- }
- super.handleMessage(msg);
- }
- };
- TimerTask task = new TimerTask(){
- public void run() {
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
Android Timer的相关操作就为大家介绍到这里。