如何使用android计时器

时间:2010-08-12 22:12:27

标签: java android timer

在尝试了解如何在android中使用计时器时遇到问题。我有一个活动,在我的onCreate方法中设置了timerTask。我按下一个按钮调用该任务,它应该做的就是附加一个textview。问题是我在timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);

收到NullPointerException

有没有明显的理由让我失踪?

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);

                }
            });

        }
}

提前致谢

凯文

0 个答案:

没有答案