onLocationChanged() is never trigered by requestLocationUpdate() - Android

前端 未结 2 1310
粉色の甜心
粉色の甜心 2020-12-22 14:09

I have used manager.requestLocationUpdates(\"gps\", 1000, 0, new LocationDetector()); to get update after every second. But this method is never triggering

2条回答
  •  粉色の甜心
    2020-12-22 14:41

    This is what a typical location request should look like:

    Note: I have Activity as a parameter because I call this from an Activity. It is in my util class.

    public static void getLocation(Activity activity) {
        final LocationListener locationListener = new LocationListener() {
            @Override
            public void onProviderEnabled(String provider) {
                Log.i(TAG, "onProviderEnabled");
            }
    
            @Override
            public void onProviderDisabled(String provider) {
                Log.i(TAG, "onProviderDisabled");
            }
    
            @Override
            public void onLocationChanged(Location location) {
                Log.i(TAG, "onLocationChanged");
            }
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.i(TAG, "onStatusChanged");
            }
        };
    
        final LocationManager locationManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
        final Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setCostAllowed(false);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);
    
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                locationManager.requestLocationUpdates(1000, 0, criteria, locationListener, null);
            }
        });
    }
    

    EDIT: like @ishmaelMakitla said,

    make sure to have the following permission:

    
    

提交回复
热议问题