-->

In Android i want to run countdown timer who can r

2019-06-14 18:34发布

问题:

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:

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
        }
    }
}