如何让在后台运行一个计时器 [英] How to make a timer run in the background

查看:325
本文介绍了如何让在后台运行一个计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何去有效地有在后台运行的定时器应用程序时,停止?现在我仪式什么也没有做,定时器将继续当应用程序已经停止,但是运行一些时候,它就会停止没有我给它的指令运行。
这就是我如何运行目前我的定时器:

How would i go about efficiently having a timer run in the background when the application is stopped? rite now i have not done anything and the timer will continue to run when the app has been stopped but some times it will stop running without me giving it the command. This is how i am currently running my timer:

    if(t == null){
   t = new Timer();
    t.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                public void run() {
                    if(DHPDPS==0){
                        money = (DPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    }else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
                        money = (DOTPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    } else{

                        money = (DPPS+Reserve);
                        Reserve = (money);
                        String end = String.format("%1f", money);
                        t1.setText("$" + end);
                    }
                    counter++;
                    //if(counter == 3000)
                    //   t.cancel();

                    // Display pay per second
                    if(counter <= DHPDPS || DHPDPS == 0){
                    t2.setText("Your pay per second is: $"+result);
                    }else{
                        t2.setText("Your pay per second is: $"+result2);
                    }
                }
            }); 
        }
    }, 20, 20);

这是在OnCreate(),谢谢!

It is declared in the onCreate(), thanks!

推荐答案

有关在后台运行的任务,你应该使用的 IntentService 。它将会继续,即使你的活动是由OS暂停或删除运行。

For tasks running in the background you should be using an IntentService. It will keep running even if your activity is paused or removed by the OS.

这篇关于如何让在后台运行一个计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆