Android 每 X 秒在服务中运行线程 [英] Android run thread in service every X seconds

查看:16
本文介绍了Android 每 X 秒在服务中运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每 X 秒运行一次的 Android 服务中创建一个线程

I want to create a thread in an Android service that runs every X seconds

我目前正在使用 ,但延迟后的方法似乎真的落后于我的应用程序.

I am currently using , but the postdelayed method seems to really lag out my app.

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    super.onStartCommand(intent, flags, startId);

    startRepeatingTask();

    return startId;
}

private final static int INTERVAL = 20000; //20 milliseconds
Handler m_handler = new Handler();

Runnable m_handlerTask = new Runnable()
{
     @Override 
     public void run() {
         // this is bad
          m_handler.postDelayed(m_handlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    m_handlerTask.run(); 
}

void stopRepeatingTask()
{
   m_handler.removeCallbacks(m_handlerTask);
   stopSelf();
}

我想做一个这样的新线程:

I want to do a new thread like this:

public void threadRun()
{
    Thread triggerService = new Thread(new Runnable(){
        public void run(){
            Looper.prepare();
            try{
                    //do stuff here?

            }catch(Exception ex){
                    System.out.println("Exception in triggerService Thread -- "+ex);
            }//end catch


        }//end run
    }, "aThread");
    triggerService.start();      

    //perhaps do stuff here with a timer?
    timer1=new Timer();

    timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL);
}

我不确定在特定时间间隔运行后台线程的最佳方法,感谢您的洞察力!

I'm not sure the best way to do a background thread to run at a certain interval, insight appreciated!

推荐答案

有多种替代方法可以做到这一点.就个人而言,我更喜欢使用 ScheduledExecutorService:

There are number of alternative ways to do this. Personally, I prefer to use ScheduledExecutorService:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
  public void run() {
    doSomethingUseful();
  }
}, 0, 2, TimeUnit.MINUTES);

这篇关于Android 每 X 秒在服务中运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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