如何让在后台运行的定时器(How to make a timer run in the backgr

2019-10-17 02:49发布

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

    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(声明),谢谢!

Answer 1:

在后台运行的任务,你应该使用IntentService 。 它将使即使你的活动被暂停或由操作系统删除运行。



Answer 2:

如果你的手机内存开始填充,将关闭未主动使用的所有活动。

对于像一个计时器可能是更好地节省启动时间为SQLite和活动时重新加载参考它作为起点来计算时间。

否则,如果你的意图计时器滴答不断把它变成一个目的服务。



文章来源: How to make a timer run in the background