返回列表 發帖

android 計時器開發

我想做一個計時器設定每隔幾分鐘就會去抓一次手機的時間

可是現在不知道程式哪裡有問題無法執行?

package com.example.taiwan;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GetTime extends Activity {

TextView tv = (TextView) findViewById(R.id.textView1);
Timer timer = new Timer(true);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_time);
timer.schedule(new timerTask(), 1000, 100000);
}

public class timerTask extends TimerTask{
public void run(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy/mm/dd HH:mm:ss);
String tm = simpleDateFormat.format(calendar.getTime());

tv.setText(tm);
}
}


}

//不同Thread,傳遞資料要用Handler

//加下列3行
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;


//以下修改
publicclassGetTimeextendsActivity{

TextViewtv;
Timertimer;

@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_time);

tv=(TextView)findViewById(R.id.textview1);
timer=newTimer(true);
timer.schedule(newtimerTask(newHandler(){
publicvoidhandleMessage(Messagem){
tv.setText(m.getData().getString(text));
}
}),1000,100000);
}

publicclasstimerTaskextendsTimerTask{
HandlermHandler;
publictimerTask(Handlerhandler){
mHandler=handler;
}
publicvoidrun(){
Calendarcalendar=Calendar.getInstance();
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat(yyyy/mm/ddHH:mm:ss);
Stringtm=simpleDateFormat.format(calendar.getTime());

Messagemsg=mHandler.obtainMessage();
Bundleb=newBundle();
b.putString(text,tm);
msg.setData(b);
mHandler.sendMessage(msg);
}
}

}

TOP

返回列表