androidandroid-gps

requestLocationUpdates() takes too much time OR it does not works at all


I have used requestLocationUpdates method inside Service in my Android application for getting updates whenever location of my device changes. I have set minTime = 0 But this requestLocationUpdates method is giving update after very long delays (that is 10 to 15 minutes, or even more). And sometimes when I run my application requestLocationUpdates mehod does not gives any update at all. And few of the times (very rare) this requestLocationUpdates method behaves as expected (gives updates continuously with 0 seconds delay). So what can be the problem? And how can I get updates continuously, every time when I run my application?

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) {}
}

Solution

  • I tried your whole code with creating new project in my laptop and run on my phone.

    Result : It's working and GPS TTF is almost 15 seconds on my phone.

    Have you tried other devices ?

    What about gps icon ? appeared, disappeared ?

    And try fused location provider to see what gonna happen, link