Android 如何使IntentService的线程保持活动状态?
我正在编写一个跟踪用户位置的测试应用程序。我的想法是,我可以启动一个服务,然后注册位置更新。目前,我正在使用IntentService来实现这一点 服务代码(不工作…)如下所示:Android 如何使IntentService的线程保持活动状态?,android,multithreading,intentservice,Android,Multithreading,Intentservice,我正在编写一个跟踪用户位置的测试应用程序。我的想法是,我可以启动一个服务,然后注册位置更新。目前,我正在使用IntentService来实现这一点 服务代码(不工作…)如下所示: public class GpsGatheringService extends IntentService { // vars private static final String TAG = "GpsGatheringService"; private boolean stopThread; // const
public class GpsGatheringService extends IntentService {
// vars
private static final String TAG = "GpsGatheringService";
private boolean stopThread;
// constructors
public GpsGatheringService() {
super("GpsGatheringServiceThread");
stopThread = false;
}
// methods
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent arg0) {
// this is running in a dedicated thread
Log.d(TAG, "onHandleIntent()");
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged()");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled()");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled()");
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged()");
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
while (!stopThread) {
try {
Log.d(TAG, "Going to sleep...");
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
stopThread = true;
}
}
目前唯一发生的事情是“去睡觉…”的输出。我需要一些机制来保持线程的活动性(因为在其他情况下,状态更新将无法访问侦听器),并且不会浪费cpu时间(我认为繁忙的循环不是首选方式)。
即使有很多其他方法可以实现应用程序行为(记录gps坐标),我还是对这种方法的解决方案感兴趣,学习解决此类问题的技术 考虑使用。这对我有用
如何使IntentService的线程保持活动状态
你没有。在这样的场景中不使用IntentService
我需要某种机制来保持线程的活动性(因为在其他情况下,状态更新将无法访问侦听器),并且不会浪费cpu时间(我认为忙循环不是首选方式)
不,在这种情况下,
服务
是可以的,因为您可以控制服务何时离开,您可以控制创建的任何线程的生存期,等等。IntentService
不适合您的预期用途,因为它控制服务何时离开,并控制线程的生存期 你为什么不使用服务而不是IntentService呢?你可能会说IntentService适合于同步后台处理,但你需要使用服务或其他东西来进行异步处理。也就是说,如果你正在调用的东西有回调,不要使用IntentService。因此,如果他想在他的IntentService中放入循环,那么@Commonware是一种不好的做法?我明白了,所以我们应该只创建服务而不是IntentService,对吗D@gumuruh:“所以,如果他想在他的IntentService中加入循环,那将是一个糟糕的做法”-IMHO,是的。在您自己的后台线程中使用常规的服务
,您可以定义自己的规则,以确定服务何时关闭,如果在线程已经运行时收到命令,该怎么办,等等。我明白了,我明白了。但是,如果我使用一个公共线程并绑定到一个处理程序@commonware?@commonware,那么有什么区别呢?在您完成的所有项目中,IntentService与Service的使用率百分比是多少?在大多数情况下,您是否使用服务?是20/80吗?我相信远程服务运行在单独的进程上,而不是线程上。我使用远程服务的处理程序中的Thread.sleep
调用对其进行了测试,整个应用程序在服务睡眠时挂起