-1

Hi Friends am developing one app in which my requirement is to run the timer in background also like popular candy crush game my actual requirement is like when i open my app first time in a day i want to start countdown timer 24:00:00 after some time suppose i leave my application and open other application during same time my countdown timer must be running it will never be pause or it will never be stop

i visit almost 8,9 tutorial but am not getting exact result please help me out what kind of class may i use or any tutorial link please thanks in advance

1 Answers1

1

You have two options: Service and storing time of app launching. Service could be killed by system at any time, so you have to save time on onDestroy method and then when system will relaunch your Service system will call onCreate method where you need to restore timer. The second method is easier. You could store current time on starting your app and then just check differences. Sample:

@Override
protected void onResume() {
    super.onResume();

    final SharedPreferences appPrefs = getSharedPreferences("appPrefs", MODE_PRIVATE);
    final long launchTime = appPrefs.getLong("launchTime", 0);
    final long currentTime = System.currentTimeMillis();

    if(launchTime == 0){
        //first launch
        appPrefs.edit().putLong("launchTime", currentTime);
    }else{
        long diff = currentTime - launchTime;
        long minutesPassed = diff / 1000 / 60;

        if(24 * 60 <= minutesPassed){
            //24 hours passed since app launching
        }else{
            //24 hours didn't passed since app launching
        }
    }
}
eleven
  • 6,779
  • 2
  • 32
  • 52
  • thanks @fox in socks let me check this solution but i have one doubt suppose this scenario is valid timer is coundwoning from 24 to 0 and i changed device time then is this scenario works?? – Android is everything for me Mar 24 '14 at 10:46
  • 1
    @VikrantAlekar `System.currentTimeMillis` returns time according to the system time so if user change system time this method will return appropriate time. Using `Service` you need the start point(`System.currentTimeMillis`) also. If you want completely independent time measuring you need to use separate server(e.g. machine where time is unchangeable). – eleven Mar 24 '14 at 11:12