简体   繁体   English

长时间运行android后台服务

[英]Run android background service for long time

I have an app that launches another app. 我有一个可以启动另一个应用程序的应用程序。 When my app goes into the background I want it to execute a method every 1 minute while in the background. 当我的应用进入后台时,我希望它在后台每1分钟执行一次方法。 The user might be in the other app for hours and I need this code to execute as long as possible. 用户可能在另一个应用程序中待了几个小时,因此我需要这段代码尽可能长的时间执行。

What is the best way to do this in Android? 在Android中执行此操作的最佳方法是什么?

The Android docs say: Android文档说:

" If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask" “如果需要让线程长时间运行,强烈建议您使用java.util.concurrent包提供的各种API,例如Executor,ThreadPoolExecutor和FutureTask”

Those utilities are a little over my head. 这些实用程序让我有些头疼。 I also need help with a background timer. 我还需要有关后台计时器的帮助。

Basically I just want this: 基本上我只想要这个:

(while my app is in background) do:
MyMethod()
Wait(1 minute)

You need to register to the alarmmanager service and invoke the your receiver every 1 minute. 您需要注册到alarmmanager服务并每1分钟调用一次接收器。 This is a good example to start with Use alarmmanager to schedule events. 使用alarmmanager安排事件开始,这是一个很好的示例

Try using the ScheduledExecutorService see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html ; 尝试使用ScheduledExecutorService,请参见http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

It has a method called scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 它有一个称为scheduleWithFixedDelay(Runnable命令,long initialDelay,long delay,TimeUnit单位)的方法

you could do 你可以做

Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(new Runnable() {
public void run() {
wait(1);
}),0,1,TimeUnit.SECONDS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM