简体   繁体   中英

Refresh map to show current location after enabling GPS setting not working

How do I refresh the map fragment after enabling the GPS settings? I am using the code below to enable the GPS from setting.

//ask for runtime permission to showing map

private void askForPermission(String permission, Integer requestCode) {
    if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
            //getActivity().finish();
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
        }
    }
}

//check the gps is enable or not
public void statusCheck() {
     manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();
    }
}

//alert dialog to enable location permission
private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();

                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

For refreshing map. Create a method like

private void refreshMap(){
if(mMap!=null){
            mMap.clear();
        }
}

You have to register broadcast receiver for that. Check the gps broadcast in documentation. You might do it twice, if there is permission for gps or not. If there is no permission you have to check the result of requestpermission method in onRequestPrrmissionResult, then register reciever there.

PS Don't forget to unregister from broadcast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM