简体   繁体   English

启用GPS设置后,刷新地图以显示当前位置

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

How do I refresh the map fragment after enabling the GPS settings? 启用GPS设置后如何刷新地图片段? I am using the code below to enable the GPS from setting. 我正在使用下面的代码来启用GPS设置。

//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. 检查文档中的gps广播。 You might do it twice, if there is permission for gps or not. 如果是否允许使用gps,您可能会做两次。 If there is no permission you have to check the result of requestpermission method in onRequestPrrmissionResult, then register reciever there. 如果没有权限,则必须在onRequestPrrmissionResult中检查requestpermission方法的结果,然后在此处注册接收者。

PS Don't forget to unregister from broadcast. PS别忘了取消广播注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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