如何使用 Target API 23 及更高版本通过 GPS 获取用户位置
Posted
技术标签:
【中文标题】如何使用 Target API 23 及更高版本通过 GPS 获取用户位置【英文标题】:How to get users Location through GPS with Target API 23 and higher 【发布时间】:2017-05-26 22:24:09 【问题描述】:我正在尝试在我的项目中实现一个 GPStracker,我想用它来获取用户的 lat、long 和 post 代码。我正在关注本教程; http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/,但是,我似乎无法使代码正常工作,经过数小时的尝试和研究,我不确定我应该做什么。我对 Android 还很陌生,所以我可能犯了一个愚蠢的错误。
当我按照发布的网站上显示的指南进行操作时,我在代码中收到一条错误消息:
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 及更高版本的问题。许多其他人发布了类似的问题,但是当我尝试为他们提供的答案时,我仍然无法让它发挥作用;例如,
我尝试实现:
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return;
我假设授予 Android 之后的权限,但它仍然不起作用。如果有一种您认为更好的获取用户位置的新方法,请指导我。
我的项目中还包含以下权限:
<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" />
【问题讨论】:
那个教程是四年半的时间。在 Android 年代,这几乎是永远的。坚持使用较新的教育材料(理想情况下,不到两年)。 FWIW,here is a sample app demonstrating getting the location while also employing runtime permissions. :) 说的对。会记住这一点,谢谢。感谢您的链接 【参考方案1】:如果您的应用面向 api 23 或更高版本,则需要在运行时请求 Location 权限。
将此代码添加到您的活动中:
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
然后,只需在 Activity 的onCreate()
中调用checkLocationPermission()
。
【讨论】:
我是否需要将它与教程中的其他代码一起包含在内,还是单独使用? 此代码仅请求位置权限。授权后怎么做,就看你自己了! (基本上,保留您现有的代码,并将其添加到它旁边) 定位权限后是否开启GPS? @KomalGupta 此答案中的代码严格用于请求您的应用程序的权限。要提示用户启用 GPS,请参阅此答案:***.com/questions/31235564/…以上是关于如何使用 Target API 23 及更高版本通过 GPS 获取用户位置的主要内容,如果未能解决你的问题,请参考以下文章
Android drawable 对于 API <23 和 API 23 及更高版本显示为拉伸
Android Edittext 不能专注于 API 22(代码在 API 23 及更高版本上运行良好)
RecyclerView wrap_content 不适用于 API 23 及更高版本
在 API 23 及更高版本中插入 SD 卡时,getExternalFilesDirs() 未在 ApplicationContext 中更新