我在我的 Android 应用程序中使用了requestLocationUpdates
方法来Service
在我的设备位置发生变化时获取更新。我已经设置minTime = 0
但是这种requestLocationUpdates
方法会在很长的延迟(即 10 到 15 分钟,甚至更多)后进行更新。有时当我运行我的应用程序时,方法requestLocationUpdates
根本没有提供任何更新。并且在少数情况下(非常罕见),此requestLocationUpdates
方法的行为符合预期(以 0 秒延迟连续提供更新)。那么可能是什么问题?每次运行我的应用程序时,我如何才能不断获得更新?
HelloService.java
public class HelloService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(MainActivity.context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
else {
manager.requestLocationUpdates("gps", 0, 0, new LocationDetector());
Toast.makeText(MainActivity.ctx, "Service Started...", Toast.LENGTH_LONG).show();
}
}
});
}
}).start();
return Service.START_STICKY;
}
}
LocationDetector.java
public class LocationDetector implements LocationListener {
@Override
public void onLocationChanged(Location location) {
/*I have used here Log.e instead of Log.d in order to get the output in clear red message that is easily readable*/
Log.e("GPS: ", location.getLatitude()+ ", " +location.getLongitude(), new Exception());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
}