赞
踩
AndroidManifest.xml
中声明权限常用的定位权限有以下两种:
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
在Android 6.0(API级别23)及以上版本,应用需要在运行时请求危险权限。以下是如何在代码中请求定位权限的示例:
在Activity中,添加检查权限和请求权限的代码:
- import android.Manifest;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import androidx.annotation.NonNull;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.app.ActivityCompat;
- import androidx.core.content.ContextCompat;
-
- public class MainActivity extends AppCompatActivity {
- private static final int PERMISSION_REQUEST_LOCATION = 1;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- // 检查定位权限
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
- != PackageManager.PERMISSION_GRANTED) {
- // 请求权限
- ActivityCompat.requestPermissions(this,
- new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
- PERMISSION_REQUEST_LOCATION);
- } else {
- // 权限已被授予,可以直接使用定位服务
- useLocationServices();
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- if (requestCode == PERMISSION_REQUEST_LOCATION) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- // 权限被授予,可以使用定位服务
- useLocationServices();
- } else {
- // 权限被拒绝,显示提示信息
- showPermissionDeniedMessage();
- }
- }
- }
-
- private void useLocationServices() {
- // 使用定位服务的代码
- }
-
- private void showPermissionDeniedMessage() {
- // 提示用户权限被拒绝的信息 如
- new AlertDialog.Builder(this)
- .setTitle("Permission Denied")
- .setMessage("Location permission is necessary for this app to function.
- Please grant the permission in app settings.")
- .setPositiveButton("OK", null)
- .show();
- }
- }
AndroidManifest.xml
中声明了服务依赖:比如高德 - <meta-data
- android:name="com.amap.api.v2.apikey"
- android:value="你的Key"></meta-data>
- <service android:name="com.amap.api.location.APSService" />
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。