有問題試圖瞭解如何在android中使用定時器。我有一個活動,在我的onCreate方法中設置了一個timerTask。我通過單擊按鈕調用該任務,並且它應該執行的操作是追加一個textview。問題是我得到一個NullPointerException在timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);
如何使用android定時器
是否有任何明顯的原因,我失蹤?現在死了 -
public class UseGps extends Activity
{
Button gps_button;
TextView gps_text;
LocationManager mlocManager;
TimerTask task;
Timer timer;
public final int TIMER_DELAY = 1000;
public final int TIMER_ONE_MINUTE = 60000;
public final int TIMER_ONE_SECOND = 1000;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps_button = (Button) findViewById(R.id.Button);
gps_text = (TextView) findViewById(R.id.Text);
task = new TimerTask() {
@Override
public void run() {
gps_text.append("Time up ");
try {
this.wait(TIMER_DELAY);
}
catch (InterruptedException e){
}
}
};
/* Use the LocationManager class to obtain GPS locations */
double gps[] = getLastKnownGPS();
gps_text.setText("Last known Location = "+gps[0]+" "+gps[1]);
gps_button.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam){
gps_text.append("\n\nSearching for current location. Please hold...");
gps_button.setEnabled(false);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);
}
});
}
}
在此先感謝
凱文
您從不分配計時器。 – Asahi 2010-08-12 22:22:02
抱歉,不確定你的意思,你能擴展嗎? 謝謝 – 2010-08-12 22:27:43
當然。在你的代碼片段中你有一個參考: 定時器計時器; 但是決不要通過調用 timer = new Timer()來分配實例。 詳情請參閱示例 – Asahi 2010-08-12 22:33:25