如何让 IntentService 的线程保持活动状态?
-
13-12-2019 - |
题
我正在编写一个测试应用程序来跟踪用户位置。我的想法是,我可以启动一项服务,然后注册位置更新。现在我正在使用 IntentService 来实现这一点。
服务代码(不起作用......)如下所示:
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;
}
}
目前唯一发生的事情是“Going to sleep...”的输出。我需要某种机制来保持线程处于活动状态(因为否则无法再访问侦听器以进行状态更新)并且不会浪费 cpu 时间(我认为繁忙循环不是首选方式)。即使有大量其他方法来实现应用程序行为(记录 GPS 坐标),我对这种方法的解决方案很感兴趣,以学习解决这种性质问题的技术!
解决方案
如何让 IntentService 的线程保持活动状态?
你不知道。你不使用 IntentService
在这样的场景中。
我需要某种机制来保持线程处于活动状态(因为否则无法再访问侦听器以进行状态更新)并且不会浪费 cpu 时间(我认为繁忙循环不是首选方式)
不,在这种情况下 Service
很好,因为您可以控制服务何时消失,您可以控制您创建的任何线程的生命周期等。 IntentService
不适合您的预期目的,因为 它 控制服务何时消失以及 它 控制线程的生命周期。
其他提示
考虑使用远程服务。它为我工作了。
不隶属于 StackOverflow