Android对LocationManager的检查权限 [英] Android check permission for LocationManager

查看:120
本文介绍了Android对LocationManager的检查权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在活动布局中单击一个按钮时,我试图显示GPS坐标.以下是单击按钮时调用的方法:

I'm trying to get the GPS coordinates to display when I click a button in my activity layout. The following is the method that gets called when I click the button:

public void getLocation(View view) {
    TextView tv = (TextView) findViewById(R.id.gps_coord_view);
    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    tv.setText("Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude());
}

我收到一条错误消息

呼叫需要许可,用户可能会拒绝它.代码应明确检查权限是否可用.

Call requires permission which may be rejected by user. Code should explicitly check to see if permission is available.

我已经在AndroidManifest中授予了这些权限.当我在调用lm.getLastKnownLocation之前添加以下内容时,该错误会得到解决,并且应用程序会编译:

I have already granted these permissions in my AndroidManifest. The error is taken care of and the app compiles when I add the following before calling lm.getLastKnownLocation:

if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return;
}

但是,当我按下调用getLocation的按钮时,该应用程序崩溃了.到底是怎么回事?有没有更好/更简单的方法来获取设备的GPS坐标?

However, the app crashes when I press the button that calls getLocation when it's clicked. What is going on? Is there better/simpler way to grab the GPS coordinates of the device?

推荐答案

对于Android API级别(23),我们需要检查权限. https://developer.android.com/training/permissions/requesting.html

With Android API level (23), we are required to check for permissions. https://developer.android.com/training/permissions/requesting.html

我遇到了同样的问题,但是以下方法对我有用,并且我能够成功检索位置数据:

I had your same problem, but the following worked for me and I am able to retrieve Location data successfully:

(1)确保清单中列出了您的权限:

(1) Ensure you have your permissions listed in the Manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

(2)确保您请求用户权限:

(2) Ensure you request permissions from the user:

if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                                                LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
        }

(3)确保使用ContextCompat,因为它与较旧的API级别兼容.

(3) Ensure you use ContextCompat as this has compatibility with older API levels.

(4)在您的位置服务或用于初始化LocationManager并获取最后一个已知位置的类中,我们需要检查权限:

(4) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:

if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }

(5)仅当我在initLocationService方法的顶部包含@TargetApi(23)后,此方法才对我有用.

(5) This approach only worked for me after I included @TargetApi(23) at the top of my initLocationService method.

(6)我还将其添加到我的gradle版本中:

(6) I also added this to my gradle build:

compile 'com.android.support:support-v4:23.0.1'

这是我的LocationService供参考:

Here is my LocationService for reference:

public class LocationService implements LocationListener  {

    //The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters

    //The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute

    private final static boolean forceNetwork = false;

    private static LocationService instance = null;

    private LocationManager locationManager;
    public Location location;
    public double longitude;
    public double latitude; 


    /**
     * Singleton implementation
     * @return
     */
    public static LocationService getLocationManager(Context context)     {
        if (instance == null) {
            instance = new LocationService(context);
        }
        return instance;
    }

    /**
     * Local constructor
     */
    private LocationService( Context context )     {

        initLocationService(context); 
        LogService.log("LocationService created");
    }



    /**
     * Sets up location service after permissions is granted
     */
    @TargetApi(23)
    private void initLocationService(Context context) {


        if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }

        try   {
            this.longitude = 0.0;
            this.latitude = 0.0;
            this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            // Get GPS and network status
            this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (forceNetwork) isGPSEnabled = false;

            if (!isNetworkEnabled && !isGPSEnabled)    {
                // cannot get location
                this.locationServiceAvailable = false;
            }
            //else
            {
                this.locationServiceAvailable = true;

                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null)   {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        updateCoordinates();
                    }
                }//end if

                if (isGPSEnabled)  {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null)  {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        updateCoordinates();
                    }
                }
            }
        } catch (Exception ex)  {
            LogService.log( "Error creating location service: " + ex.getMessage() );

        }
    }       


    @Override
    public void onLocationChanged(Location location)     {
        // do stuff here with location object 
    }
}

到目前为止,我仅使用Android Lollipop设备进行了测试. 希望这对您有用.

I tested with an Android Lollipop device so far only. Hope this works for you.

这篇关于Android对LocationManager的检查权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆