如何在服务中添加天文台?

时间:2016-02-25 08:32:26

标签: android service counter chronometer

我正在试图在服务中添加Chronometer并获取值。但我没有得到正确的天文数字值。

public class NewLocationUpdateService extends Service  {
    Chronometer chronometer;
     private static final int LOC_API_CALL_INTERVAL = 60 * 1000;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        chronometer = new Chronometer(NewLocationUpdateService.this);
                chronometer.setBase(SystemClock.elapsedRealtime());
                chronometer.start();

        startTimer();

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {


        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);

    }
  @Override
    public void onDestroy() {
        super.onDestroy();


        stopTimer();

    }

//Timer related functions

    private void startTimer(){
        if(timer!=null ){
            return;
        }
        timer=new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                long millis=SystemClock.elapsedRealtime() - chronometer.getBase();
                long seconds = (millis / 1000) % 60;
                Log.e("timefortest", "" + seconds);
             }
        }, LOC_API_CALL_INTERVAL, LOC_API_CALL_INTERVAL);
    }

    private void stopTimer(){

        if(null!=timer){
            timer.cancel();
            timer=null;
        }
    }


}

我得到的输出

 E/timefortest: 7
 E/timefortest: 1
 E/timefortest: 0
 E/timefortest: 5
 E/timefortest: 0
 E/timefortest: 0
 E/timefortest: 0
 E/timefortest: 0
 E/timefortest: 1
 E/timefortest: 0
 E/timefortest: 2

我期待

 E/timefortest: 60
 E/timefortest: 120
 E/timefortest: 180
 E/timefortest: 240

让我知道我做错了什么。我的目的是我需要在服务中启动计数器,我需要获取值。

1 个答案:

答案 0 :(得分:0)

我认为你应该删除mod 60.这是一个例子。

 long timeWhenStopped =  SystemClock.elapsedRealtime() - chronometer.getBase();
    int seconds = (int) timeWhenStopped / 1000;