Timer 跟线程的安全有关,所以我们要用Handler来处理:
代码如下:(此Demo主要是演示camera的self Timer 的功能)
package com.example.mytimer;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class myTimer extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private static final int NOTIFY = 1111;
private Button mBtnStart;
private Timer mTimer;
private TimerTask mTTask;
int mCount = 0;
public Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case NOTIFY:
if (mCount > 3)
{
mTimer.cancel();
mTTask.cancel();
mCount = 0;
}
else {
Toast.makeText(getApplicationContext(), String.valueOf(mCount), Toast.LENGTH_SHORT).show();
}
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBtnStart = (Button)findViewById(R.id.start);
mBtnStart.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mTimer = new Timer();
mTTask = new myTaskTimer();
mTimer.schedule(mTTask, 0, 1000);
break;
}
}
class myTaskTimer extends TimerTask{
@Override
public void run(){
Message message = new Message();
message.what = NOTIFY;
mCount++;
mHandler.sendMessage(message);
}
}
}
Note: 如果你已取消了当前的Timer, 要再次调用的话,你需要重新New一个,因为只有在Timer的构造函数才会调线程的start方法。