【发布时间】:2016-02-05 05:58:03
【问题描述】:
我有一个在远程进程上运行的服务(通过 AIDL 接口)。这是一项不可阻挡的服务(在启动完成时开始并持续到卸载应用程序)。该服务一直在监听 UDP 套接字。我想每 30 分钟在该服务中运行一次功能(负责通过 udp 套接字向服务器发送 ping 消息)。
我尝试启动线程并休眠 30 分钟,但没有成功
new Thread(new Runnable() {
public void run() {
while (true) {
try {
sendPingMessage();
Thread.currentThread().sleep(1000 * 60 * 30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
这个函数在任意时间内调用。不完全是在 30 分钟内。
还尝试了定时器任务、处理程序和ScheduledExecutorService,也没有运气
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate (new Runnable() {
public void run() {
sendPingMessage();
}
}, 0, 30, TimeUnit.MINUTES);
似乎问题出在 android 深度睡眠模式 [http://binarybuffer.com/2012/07/executing-scheduled-periodic-tasks-in-android][1]
我也尝试过使用 AlarmManger。但是我不能在单独的班级中使用广播接收器作为警报管理器。由于我想从 android 远程服务发送 ping 消息(我无法连接/绑定到广播接收器内的远程服务)
解决我的问题的最佳方法是什么?我可以在我的服务类中使用警报管理器广播接收器(不使用单独的广播接收器类)吗?
【问题讨论】:
-
在你的广播接收器中启动你的服务,不要绑定它,绑定是不可能的
-
不,我不想在广播接收器中启动服务,服务已经启动/运行(它是一个不可停止的服务)。我想连接到该服务以发送 ping 消息(通过该服务发送 ping 消息)
-
是的,我知道,唯一的方法是致电
startService并在onStartCommand中获得通知,正如我所说,您不能从广播接收器中致电bindService
标签: android multithreading scheduled-tasks android-handler aidl