gpt4 book ai didi

Android 每 X 秒运行一次服务线程

转载 作者:可可西里 更新时间:2023-11-01 19:08:39 25 4
gpt4 key购买 nike

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

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

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

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

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

我不确定让后台线程以特定时间间隔运行的最佳方法,不胜感激!

最佳答案

有多种替代方法可以做到这一点。就个人而言,我更喜欢使用 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 秒运行一次服务线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8230606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com