测试Timer

测试Android中Timer使用MainActivity

package com.einverne.testtimer;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private static String TAG = "EV_DEBUG";
private Timer timer;
Integer integer;

private TextView tv;
private Button button_start;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv = (TextView) findViewById(R.id.textView_time);
button_start = (Button) findViewById(R.id.button_start);

integer = new Integer(0);
new TimeThread().start();

findViewById(R.id.button_start).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
timer = new Timer();
integer = 0;
timer.schedule(new timerTask(), 0, 1000);
button_start.setEnabled(false);
}
});

findViewById(R.id.button_end).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
timer.cancel();
button_start.setEnabled(true);
}
});



}

public class timerTask extends TimerTask {

@Override
public void run() {
// TODO Auto-generated method stub
integer++;
String time = integer.toString();
Log.d(TAG, time);
}
}

public class TimeThread extends Thread {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
tv.setText(integer.toString());
break;

default:
break;
}
}
};
@Override
public void run() {
do {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);

} catch (InterruptedException e) {
e.printStackTrace();
}

} while (true);
}
}

@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;
}

}

via Blogger http://www.einverne.tk/2013/04/timer.html

Advertisements

About Ein Verne

獨立之人格 自由之精神
此条目发表在Uncategorized分类目录。将固定链接加入收藏夹。

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s