我已经阅读了开发者网站和StackOverflow上大部分关于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活动通信,但由于我在另一个线程中启动服务(通过清单中的“进程”指令),我需要使用AIDL吗?
我还尝试使用AsyncTask而不是扩展Service,但它似乎更适合运行任务然后终止。
while (keepGoing)
- 如果这段代码在另一个线程中,而不是将keepGoing
设置为 false 的线程,则keepGoing
必须是volatile
的。请阅读Java内存模型的相关知识。 - Mr_and_Mrs_D