我正在编写一个跟踪用户位置的测试应用程序。这个想法是我可以启动一个服务,然后注册位置更新。现在我正在为此使用 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 坐标),我也对这种方式的解决方案感兴趣,以学习解决这种性质问题的技术!