计时器在Android的服务 [英] Timer in Android Service

查看:109
本文介绍了计时器在Android的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Android服务,它可以检查每15分钟需要的文件。

有关这,我创建了播放使用TTS每十10秒文字的示例程序。而且还使用了警报管理器来调用服务,每30秒

这项服务是完全打电话,甚至TTS完美播放的第一次,但在该服务在50秒后再次调用,计时器没有启动从0而不是从11开始,12,13 - 尽管我已经给取消()。

一些身体可以帮助我如何解决此问题?

下面是code:

 公共类ServiceLocation扩展服务实现OnInitListener
{文字转语音健谈;
定时器T;
公众诠释时间= 0;    @覆盖
公共无效的onCreate()
{
    super.onCreate();
    Log.e(LOCATION1,里面的onCreate);
}公共无效调用onStart(意向意图,诠释startId)
{
    super.onStart(意向,startId);    T =新的Timer();
    Log.e(LOCATION1,内部调用onStart);    健谈=新的文字转语音(这一点,这一点);
    测试方法();
 } 公共无效TestMethod的()
 {
    //设置日程表功能和速率
    t.scheduleAtFixedRate(新的TimerTask(){        @覆盖
        公共无效的run(){            时间+ = 1;
            字符串todis =将String.valueOf(时间);
            如果(todis.contains(20))
            {                talker.speak(测试服务的应用程序,TextToSpeech.QUEUE_ADD,NULL);                t.cancel();
                t.purge();
            }
        }    },0,1000);
}  公共无效的OnInit(INT状态)
  {
   talker.speak(测试服务的应用程序,TextToSpeech.QUEUE_ADD,NULL);
  }
 }


解决方案

在你的在onStart()方法,则需要初始化定时器(),但你必须检查的定时器运行?如果正在运行则取消并重新开始一个新的计时器。下面是示例code:

 公共静态最后长NOTIFY_INTERVAL = YOUR_REQUIRED_INTERVAL_IN_SE code * 1000;//另一个线程,以避免崩溃运行
私人处理程序yourHandler =新的处理程序();
//定时器处理
私人定时器yourTimer = NULL;@覆盖
公共无效的onCreate(){
    //如果取消已经存在
    如果(yourTimer!= NULL){
        yourTimer.cancel();
    }
        //重新创建新
        yourTimer =新的Timer();    //计划任务
    yourTimer.scheduleAtFixedRate(新TimeDisplayTimerTask(),0,NOTIFY_INTERVAL);
}

下面是你的 TimeDisplayTimerTask()

 类TimeDisplayTimerTask扩展的TimerTask {    @覆盖
    公共无效的run(){
        //另一个线程上运行
        yourHandler.post(新的Runnable(){            @覆盖
            公共无效的run(){
                //显示敬酒
                Toast.makeText(getApplicationContext(),一些信息,
                        Toast.LENGTH_SHORT).show();
            }        });
    }

要取消计时器你可以调用这个

 如果(yourTimer!= NULL){
            yourTimer.cancel();
        }`

注:


  1. 固定速率定时器(scheduleAtFixedRate())是基于起始时间(因此每个迭代将在的startTime + iterationNumber * delayTime执行)。 链接这里

  2. 要了解有关附表以及定时器任务然后查看此链接

感谢。对不起,我英语不好。

I want to create an android service that can check on required files every 15 mins.

For which, I have created a sample program that plays a text using TTS every ten 10 seconds. And also used a alarm manager to call the service every 30 seconds

The service is call perfectly and even the TTS is played perfectly the first time but when the service is called again after 50 seconds, the timer is not starting from 0 instead starts from 11, 12, 13 - even though I have given cancel().

Can some body help me out on how to solve this?

Below are the code:

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

解决方案

In your onStart() method you are initializing the Timer() but you have to check is the timer is running? If it is running then cancel it and start a new timer. Here is the sample code:

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

Here is your 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();
            }

        });
    }

To cancel the timer you can just call this

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

Notes:

  1. Fixed-rate timers (scheduleAtFixedRate()) are based on the starting time (so each iteration will execute at startTime + iterationNumber * delayTime). Link here
  2. To learn about on Schedule and timer task then view this Link

Thanks. Sorry for bad English.

这篇关于计时器在Android的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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