简体   繁体   中英

elapsed time using System.currentTimeMillis not working on android

please i'm a having a problem with getting the elapsed time between performing some actions. The code is meant to perform an action after 1 mins(60,000 millisecs.) but when i run the code on my emulator, the elapsed time difference is usually smaller then expected and often close to the value in Thread.sleep(). i have tried using System.nanoTime() and even SystemClock.uptimeMillis() ... i did a similar thing in normal java environment and it worked fine . could the problem be from the emulator and is there a way to do this?

     long startTime=0;
     long elapsedTime=0;
     long totalTime = 0;

    @Override
    public void run() {
        // TODO Auto-generated method stub

        while (running) {

            startTime = System.currentTimeMillis();
            totalTime += elapsedTime;
            Log.d("elapsed","displaying time...."+elapsedTime);

            if(totalTime > 60000){
                Log.d("mins","one mins gone");
                totalTime = 0;
            }

              // do some other things here

         try {
            Thread.sleep(9000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


            elapsedTime = System.currentTimeMillis() - startTime;

        }

    }

System.currentTimeMillis() should work. However I am not sure if that is appropriate for your situation. Putting a thread into sleep is not the best way to preform time related tasks.

If you are using version 5.0, you can make use of the JobScheduler API.

For versions below 5.0, try using AlarmManager for either one time or recurring alarms.

    AlarmManager alarm=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, _YOURBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 9000 , pi);

You need to implement aa broadcast reveiver which will be triggered when it is time.

That is because you are assigning the startTime in the while loop and that means that in the last iteration of the loop it's assigned to the time of that so It will be calculated as the thread sleeping time only as you mentioned. You should assign it before the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM