如何使用 dexter 获取 Google 地图位置权限

Posted

技术标签:

【中文标题】如何使用 dexter 获取 Google 地图位置权限【英文标题】:How to get Google map Location Permission using dexter 【发布时间】:2021-01-04 04:27:43 【问题描述】:
package com.example.myapplication.ui.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.example.myapplication.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

public class HomeFragment extends Fragment implements OnMapReadyCallback 


    private GoogleMap mMap;
    private HomeViewModel homeViewModel;


    //   Location
    private FusedLocationProviderClient fusedLocationProviderClient;
    private LocationRequest locationRequest;
    private LocationCallback locationCallback;

    SupportMapFragment mapFragment;

    @Override
    public void onDestroy() 
        fusedLocationProviderClient.removeLocationUpdates(locationCallback);
        super.onDestroy();

    

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) 
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        init();


        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        return root;
    

    private void init() 
        locationRequest = new LocationRequest();
        locationRequest.setSmallestDisplacement(10f);
        locationRequest.setInterval(50000);
        locationRequest.setFastestInterval(3000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        locationCallback = new LocationCallback() 

            @Override
            public void onLocationResult(LocationResult locationResult) 
                super.onLocationResult(locationResult);
                LatLng newposition = new LatLng(locationResult.getLastLocation().getLongitude(),
                        locationResult.getLastLocation().getLatitude());
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newposition, 18f));
            
        ;
    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;

//        Check Permission
        Dexter.withContext(getContext())
                .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new PermissionListener() 
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) 
                        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
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        
                        mMap.setMyLocationEnabled(true);
                      mMap.getUiSettings().setMyLocationButtonEnabled(true);
                      mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() 
                          @Override
                          public boolean onMyLocationButtonClick() 
                              fusedLocationProviderClient.getLastLocation()
                                      .addOnFailureListener(new OnFailureListener() 
                                          @Override
                                          public void onFailure(@NonNull Exception e) 
                                              Toast.makeText(getContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                                          
                                      )
                                      .addOnSuccessListener(new OnSuccessListener<Location>() 
                                          @Override
                                          public void onSuccess(Location location) 

                                          
                                      )
                          
                      );
                    

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) 
                        Toast.makeText(getContext(), "Permission"+permissionDeniedResponse.getPermissionName()+""
                                +"was denied!", Toast.LENGTH_SHORT).show();
                    

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) 

                    
                ).check();

        try 
            boolean success = googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
            if(!success)
                Log.e("ERROR", "Style parsing error");
            
        catch(Resources.NotFoundException e)
            Log.e("ERROR", e.getMessage());
        


    

我是编程新手。

排队

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

必需类型:上下文 提供:PermissionListener 这应该被一些东西取代,但我不知道是什么。请帮忙

【问题讨论】:

【参考方案1】:

ActivityCompat.checkSelfPermission() 接受两个参数,其中第一个是主活动的上下文。 由于您是从权限侦听器回调内部调用该方法,因此关键字this 指的是PermissionListener 对象,而不是上下文。您应该使用主要活动的上下文来代替 this 关键字。 由于您在片段中,因此您需要获取主要活动的上下文。这可以使用 onAttach 回调提供的 Context 参数来完成。

public class HomeFragment extends Fragment implements OnMapReadyCallback 
    Context ctx;
    @Override
    public void onAttach(Context context) 
        super.onAttach(context);
        ctx=context;
    
//Other stuff

将上下文对象 (ctx) 传递给 ActivityCompat.checkSelfPermission() 方法。

【讨论】:

以上是关于如何使用 dexter 获取 Google 地图位置权限的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 TabLayout 在 ViewPager 中的 Google 地图片段中获取当前位置

如何通过滑行在 Google 地图上的 infoWindow 中获取图像 - Android

如何从 Google 地图位置获取详细信息?

如何使用 Google Maps JavaScript API v3 在谷歌地图中获取查看区域中心的坐标

使用 Google 地图获取路线问题

使用 Google 静态地图检索经度/纬度的问题