【问题标题】:Self permission wrong for Google Map inside fragment activity谷歌地图在片段活动中的自我许可错误
【发布时间】:2018-12-09 10:24:50
【问题描述】:

我正在尝试将 Google 地图放入片段中,这是我尝试初始化其权限检查时的错误。这是我的

MapFragment.java

public class MapFragment extends  Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
private static final int MY_REQUEST_INT = 177;


private static final String TAG = "MapFragment";

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_map, container, false);
    mMapView = (MapView) mView.findViewById(R.id.map);
    if (mMapView != null) {
        mMapView.onCreate(null);
        mMapView.onResume();
        mMapView.getMapAsync(this);
    }
    return mView;

}


@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;



    /* check location's permission.*/

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //code for permission not granted.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_INT);
        }
        return;
    } else {


        //code for permission granted.
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);

    }


   }
}

错误:

【问题讨论】:

    标签: android google-maps android-fragments


    【解决方案1】:

    this 正在获取应用程序。您需要使用当前活动 - 或者在具有片段的活动的情况下。

    ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
         != PackageManager.PERMISSION_GRANTED) 
    

    【讨论】:

      【解决方案2】:

      当您调用 checkSelfPermission 的方法需要您的活动上下文时,您正在尝试传递片段的上下文。

      尝试使用 getActivity()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        • 2018-04-08
        • 2020-02-06
        • 1970-01-01
        • 2020-03-14
        • 2016-03-25
        • 2023-04-08
        相关资源
        最近更新 更多