在开发人员网站上阅读了大多数关于Android服务的可用文档,以及在这里的计算器中,我仍然对在单独任务中运行服务的几个方面感到困惑。希望有人能把我放在正确的轨道上。如何在Android服务中启动长时间运行的后台任务
比方说,我们有繁琐的业务框架,如
public class HliService extends Service {
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
}
}
,并在清单中,我有
<service android:name=".HliService" android:process=":HLI_Comms"/>
,这样服务在自己的线程中运行。
该服务的目的是提供一个后台任务,将 与使用TCP套接字的设备进行通信并执行其他操作。在忽略电池问题等风险,基本上我希望它永远运行。
喜欢的东西
// Method that communicates using a TCP socket, and needs to send
// information back to the activity and receive messages from activity
// not shown here.
private void dummytask() {
boolean keepGoing = true;
while (keepGoing) {
// do useful stuff in here
// sets keepGoing false at some point
}
stopSelf();
}
什么是发起这种方法/任务的最佳方法是什么?
我看过使用消息处理程序和活套的开发人员站点中的代码,我只能部分理解,但它看起来非常复杂,可能比我需要的更多?
我不相信我可以从onCreate()
或onStartCommand()
调用此方法,因为从系统调用时都不会完成?我应该用计时器还是闹钟启动它?
我需要添加一个消息处理程序来与gui活动进行通信,但由于我在另一个线程中启动服务(凭借清单“process”指令),是否需要使用AIDL ?
我也看过使用AysnchTask而不是扩展Service,但它似乎更适合运行任务,然后终止。
'while(keepGoing)' - 如果这是另一个线程,而不是将keep_inging设置为false的线程'keepGoing'必须是'volatile' - 在Java内存模型上读取 –
请参阅此答案可能帮助您。 [此处输入链接的描述] [1] [1]:http://stackoverflow.com/a/13783477/2165080 –