In Android i want to run countdown timer who can run in background also

删除回忆录丶 提交于 2019-12-08 14:06:44

问题


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


来源:https://stackoverflow.com/questions/22606294/in-android-i-want-to-run-countdown-timer-who-can-run-in-background-also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!