获取变化的位置

时间:2018-07-07 13:31:20

标签: android

我正在尝试获取用户的位置,因为它发生了变化。但是永远不会调用onLocationChanged方法。我尝试了多种解决方案,或者尝试寻找其他一些代码,但从未成功。

这是我首先获得位置的方法:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
                    // Android 4.3
                    // Parallel AsyncTasks are not possible unless using executeOnExecutor
                    ffmpegExecuteAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } else { // Below Android 3.0
                    // Parallel AsyncTasks are possible, with fixed thread-pool size
                    ffmpegExecuteAsyncTask.execute();
                }

覆盖方法:

private void getDeviceLocation() {
    Log.d(TAG, "getDeviceLocation: getting the current device's location");
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());

    try {
        if (mLocationGranted) {

            Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {

                    if (task.isSuccessful()) {
                        Log.d(TAG, "device location found");
                        currentLocation = (Location) task.getResult();
                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location");

                    } else {
                        Log.d(TAG, "onComplete:  current location is null");
                        Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();

                    }
                }
            });
        }

    } catch (SecurityException e) {
        Log.e(TAG, "SecurityException :  " + e.getMessage());
    }


}

1 个答案:

答案 0 :(得分:0)

您可以使用BroadcastReceiver来检测何时更改位置:

        android.location.Location location;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 meter

    // The minimum time beetwen updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 15*1000; // 15 second

    BroadcastReceiver gpsLocationChangeReciever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

              // if location is changed

                setLocation(getLocation());

            } else {
               // 
            }


        }
    };

这是在广播内部调用的getLocation方法:

public android.location.Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            android.location.LocationListener locationListener = new MyLocationListener();

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // location service disabled
            } else {
                this.canGetLocation = true;

                // if GPS Enabled get lat/long using GPS Services

                if (isGPSEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);

                    Log.d("GPS Enabled", "GPS Enabled");

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        //updateGPSCoordinates();
                    }
                }

                // First get location from Network Provider
                if (isNetworkEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);

                        Log.d("Network", "Network");

                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            //updateGPSCoordinates();
                        }
                    }

                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
            Log.e("Error : DestinationTo",
                    "Impossible to connect to LocationManager", e);
        }

        return location;
    }

此处为mylocationClassListener

 private class MyLocationListener implements android.location.LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
    // do whatever you want


    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }


}

在主要活动中,您可以注册广播:

registerReceiver(gpsLocationChangeReciever, new IntentFilter("android.location.PROVIDERS_CHANGED"));

确保首先获得locationPermission

相关问题