1. 在AndroidManifest.xml
中声明权限
常用的定位权限有以下两种:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
2. 在代码中请求权限
在Android 6.0(API级别23)及以上版本,应用需要在运行时请求危险权限。以下是如何在代码中请求定位权限的示例:
(1) 检查并请求权限
在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;@Overrideprotected 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();}}@Overridepublic 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();}
}
4. 其他注意事项
- 确保在
AndroidManifest.xml
中声明了服务依赖:比如高德<meta-dataandroid:name="com.amap.api.v2.apikey"android:value="你的Key"></meta-data> <service android:name="com.amap.api.location.APSService" />