【问题标题】:Timer in Android ServiceAndroid 服务中的计时器
【发布时间】:2013-04-20 06:45:15
【问题描述】:

我想创建一个可以每 15 分钟检查一次所需文件的 android 服务。

为此,我创建了一个示例程序,它使用 TTS 每 10 秒播放一次文本。并且还使用了一个警报管理器,每 30 秒调用一次服务

服务被完美调用,甚至第一次完美播放 TTS 但是当服务在 50 秒后再次被调用时,计时器不是从 0 开始而是从 11、12、13 开始 - 即使我已经给出取消()。

有人可以帮我解决这个问题吗?

下面是代码:

public class ServiceLocation extends Service implements OnInitListener
{

TextToSpeech talker;
Timer t;
public int time = 0;

    @Override
public void onCreate() 
{
    super.onCreate();
    Log.e("Location1", "Inside onCreate");
}

public void onStart(Intent intent, int startId) 
{
    super.onStart(intent, startId);

    t = new Timer();
    Log.e("Location1", "Inside onStart");

    talker = new TextToSpeech(this, this);
    testMethod();
 }

 public void testMethod()
 {      
    //Set the schedule function and rate
    t.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run()    {  

            time += 1;
            String todis = String.valueOf(time);


            if(todis.contains("20"))
            {

                talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);

                t.cancel();
                t.purge();
            }
        }   

    }, 0, 1000);
}

  public void onInit(int status) 
  {             
   talker.speak("Testing Service in a App",TextToSpeech.QUEUE_ADD,null);
  }
 }

【问题讨论】:

    标签: java android service


    【解决方案1】:

    TimerTask 刷新;

                      timer = new Timer();    
                     refresher = new TimerTask() {
                         public void run() {
    
    
                            //your code 
    
                         };
                     };
                    first event immediately,  following after 1 seconds each
                     timer.scheduleAtFixedRate(refresher, 0,1000); 
    

    //您可以将1000更改为您需要的时间。 1000 等于 1 秒。

    您可以将此代码放在您的服务类 oncreate 中。您可以在代码部分中每十五分钟调用一次您想要调用的方法。

    希望对你有所帮助。

    【讨论】:

      【解决方案2】:

      您必须每 10 秒重置一次计时器。

      示例代码:

       public void startTimer(){
        t = new Timer();   
        task = new TimerTask() {
      
          @Override
         public void run() {
          runOnUiThread(new Runnable() {
      
            @Override
           public void run() {
            TextView tv1 = (TextView) findViewById(R.id.timer);
            tv1.setText(time + "");
            if (time > 0)
             time -= 1;
            else {
             tv1.setText("Welcome");           
            }
           }
          });
         }
        };
        t.scheduleAtFixedRate(task, 0, 1000);
       }
      

      有关简短示例,请参阅我的 blog post

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        在您的onStart() 方法中,您正在初始化Timer(),但您必须检查计时器是否正在运行?如果它正在运行,则取消它并启动一个新的计时器。这是示例代码:

        public static final long NOTIFY_INTERVAL = YOUR_REQUIRED_INTERVAL_IN_SECODE* 1000;
        
        // run on another Thread to avoid crash
        private Handler yourHandler = new Handler();
        // timer handling
        private Timer yourTimer = null;
        
        @Override
        public void onCreate() {
            // cancel if already existed
            if(yourTimer != null) {
                yourTimer.cancel();
            }
                // recreate new
                yourTimer = new Timer();
            
            // schedule task
            yourTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
        }
        

        这是你的TimeDisplayTimerTask()

         class TimeDisplayTimerTask extends TimerTask {
        
            @Override
            public void run() {
                // run on another thread
                yourHandler.post(new Runnable() {
        
                    @Override
                    public void run() {
                        // display toast
                        Toast.makeText(getApplicationContext(), "some message",
                                Toast.LENGTH_SHORT).show();
                    }
        
                });
            }
        

        要取消计时器,您可以调用它

        if(yourTimer != null) {
                    yourTimer.cancel();
                }`
        

        注意事项:

        1. 固定速率计时器 (scheduleAtFixedRate()) 基于开始时间(因此每次迭代将在 startTime + iterationNumber * delayTime 处执行)。 Link here
        2. 要了解计划和计时器任务,请查看this Link

        谢谢。抱歉英语不好。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-29
          相关资源
          最近更新 更多