如何使用Target API 23和更高版本通过GPS获取用户位置 [英] How to get users Location through GPS with Target API 23 and higher

查看:78
本文介绍了如何使用Target API 23和更高版本通过GPS获取用户位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中实现一个GPStracker,我希望该GPStracker可以使用户获得经纬度,经度和邮政编码.我正在关注本教程; http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/,但是,我似乎无法使代码正常工作,经过数小时的尝试和研究,我不确定应该怎么做.我是Android的新手,所以我可能犯了一个愚蠢的错误.

I am trying to implement a GPStracker in my project which I want to use to get users lat, long and post code. I am following this tutorial; http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/, however, I can't seem to get the code working and after hours trying and researching I am not sure what I should do. I am fairly new to Android so I am probably making a silly mistake.

当我按照发布的网站上显示的指南进行操作时,我的代码收到一条错误消息,提示:

When I follow the guide as shown on the website posted I get an error message on my code saying:

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`

在线:

            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

我正在使用API​​ 25,使用片段并在线搜索,这似乎是API 23及更高版本的问题.许多其他人也发布了类似的问题,但是当我尝试为他们提供的答案时,仍然无法正常工作.例如

I am using API 25, working with fragments and searching online this seems to be a problem with API 23 and above. Many others have posted a similar questions but when I try the answers provided for them I still can't get it to work; for example,

我尝试实施:

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

我认为授予Android的权限是在此之后,但仍然无法正常工作.如果有您认为更好的获取用户位置的新方法,请您指导我.

Which I assume grants the permission Android is after but it still doesn't work. If there is a new way of getting users location that you think is better please can you direct me to that.

我在我的项目中也包含以下权限:

I have also included following permissions in my project:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

推荐答案

如果您的应用定位到api 23或更高版本,则需要在运行时请求位置"权限.

If your app targets api 23 or above, you need to request the Location permission at runtime.

将此代码添加到您的活动中:

Add this code to your Activity:

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(this)
                    .setTitle("Location Permission Needed")
                    .setMessage("This app needs the Location permission, please accept to use location functionality")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MapLocationActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION );
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION );
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                     //Permission was granted, do your thing!
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

然后,只需在活动的onCreate()中调用checkLocationPermission().

Then, just call checkLocationPermission() in onCreate() of the Activity.

这篇关于如何使用Target API 23和更高版本通过GPS获取用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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