Android broadcast gps turned on update location

ε祈祈猫儿з 提交于 2019-12-13 02:48:49

问题


Well even having a lot of reading here, i can't figure out the issue. It looks like i never get gps turned on event.

After some checking in debug, the flag isGps is correct. But as a result, user alert works nice but not update location. I just want to add a marker when gps is turned on and it looks like something is not correctly synchronised here.

And that even with high accuraty location.

I use this code from my fragment.

public class MapDialogFragment extends DialogFragment
        implements OnMapReadyCallback, GoogleMap.OnMarkerDragListener {

.....

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

                if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {


                    boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

                    if(isGPS){
                        // never goes here WHEN GPS TURNED ON !!! WHY ?? MAKES ME CRAZY
                        // + how get current location here ? is updateMyLocation call ok ?
                        updateMyLocation();
                    }
                    else{
                         // user alert
                         Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.message_location_error_gps_off), Toast.LENGTH_LONG).show();
                    }
                }
            }
        };

        @Override
        public void onResume() {
            super.onResume();
            getContext().registerReceiver(mGpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
        }

        @Override
        public void onPause() {
            super.onPause();
            getContext().unregisterReceiver(mGpsSwitchStateReceiver);
        }

     private void updateMyLocation(){
            Task locationResult = mFusedLocationProviderClient.getLastLocation();
            locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful() && task.getResult() != null) {
                        // Set the map's camera position to the current location of the device.
                        mLastKnownLocation = (Location) task.getResult();
                        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                new LatLng(mLastKnownLocation.getLatitude(),
                                        mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));

                        latitude = mLastKnownLocation.getLatitude();
                        longitude = mLastKnownLocation.getLongitude();

                        // add marker
                        buildMarkerFromLocation();

                    } else {
                        Log.d(TAG, "Current location is null. Using defaults.");
                        Log.e(TAG, "Exception: %s", task.getException());
                    }
                }
            });
        }
...
}

So here is my logic :

  1. Check if GPS is turned on
  2. If it is send mFusedLocationProviderClient.getLastLocation() request
  3. Get the result but always get no result when GPS is just turned on

So basically, how to provide a default location without hard code one ?

Here is more information about google api page :

The getLastLocation() method returns a Task that you can use to get a Location object with the latitude and longitude coordinates of a geographic location. The location object may be null in the following situations:

  1. Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.

  2. The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.

  3. Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.

Hope i will solve this with your help. Should be something obvious but i dunno what is going wrong...


回答1:


since you receive the event, that means it has nothing to do with the device itself, and looks like it's in your update location, method in my case I'm using 'OnSuccessListener' not 'OnCompleteListener', I don't know if that would be an issue or not, but anyhow that's how I update the location at my side:

/**
 * To get the current MapLocation and add marker at that location
 */
@SuppressLint("MissingPermission")
private void setCurrentLocation() {
    try {
        FusedLocationProviderClient locationClient = new FusedLocationProviderClient(getActivity());
        if (checkLocationPermissions()) {
            Task<Location> currentLocationTask = locationClient.getLastLocation(); // already checked
            currentLocationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    try {
                        // Now, add the required Marker
                        addMarker(new LatLng(location.getLatitude(), location.getLongitude()));
                    } catch (NullPointerException npe) {
                        npe.printStackTrace();
                        Toast.makeText(getActivity(), getResources().getString(R.string.cannot_get_location), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

/**
 * Adding a Marker at the Map
 *
 * @param point the point contains the latitude and longitude to add the marker at
 */
private void addMarker(LatLng point) {
    try {
        marker.remove();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }
    MarkerOptions markerOptions = new MarkerOptions().position(
        new LatLng(point.latitude, point.longitude)).title(getAddressAtLocation(point));
    marker = mMap.addMarker(markerOptions);
    currentChosenLocation = point;
}


来源:https://stackoverflow.com/questions/58837839/android-broadcast-gps-turned-on-update-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!