android {
compileSdkVersion 28
defaultConfig {
applicationId "com.xd.gps"
minSdkVersion 21
// 目标sdk版本<29,文件读写在Android10上可正常使用;
// 目标sdk版本=29,若覆盖安装(目标sdk版本从<29升到29),则Android10上可正常读写;
// 若卸载后再安装,则Android10上不能读写,需要使用存储访问框架;
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
}
/**
* Android 10及以上申请权限
*/
private String[] permissionsQ = new String[] {
// 定位权限
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
// 编译版本小于29,不能使用Manifest.permission.ACCESS_BACKGROUND_LOCATION
"android.permission.ACCESS_BACKGROUND_LOCATION",
};
/**
* Android10以下申请权限
*/
private String[] permissionsO = new String[] {
// 定位权限
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
};
onCreate 中添加:
String[] permissions = permissionsO;
// 编译版本小于29,不能使用Build.VERSION_CODES.Q
if (Build.VERSION.SDK_INT >= 29) {
permissions = permissionsQ;
}
if (EasyPermissions.hasPermissions(this, permissions)) {
onPermissionsGranted(REQUEST_CODE_PERMISSION, null);
} else {
EasyPermissions.requestPermissions(this, "请允许软件获取位置及读写权限,否则将无法正常运行!", REQUEST_CODE_PERMISSION, permissions);
}
实现EasyPermissions.PermissionCallbacks
的接口:
@Override
public void onPermissionsGranted(int requestCode, @NonNull List perms) {
requestLocation();
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List perms) {
Toast.makeText(this, "没有获取到权限,软件将退出!", Toast.LENGTH_LONG).show();
finish();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (EasyPermissions.hasPermissions(this, permissions)) {
onPermissionsGranted(REQUEST_CODE_PERMISSION, null);
} else {
onPermissionsDenied(requestCode, null);
}
}
GpsStatus.NmeaListener
和OnNmeaMessageListener
监听NMEAprivate void requestLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 注册位置服务,获取系统位置
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
// 监听NMEA
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (nmeaListener == null) {
nmeaListener = new OnNmeaMessageListener() {
@Override
public void onNmeaMessage(String nmea, long l) {
receivedNmea(nmea);
}
};
}
locationManager.addNmeaListener(nmeaListener);
} else {
if (nmeaListenerOld == null) {
nmeaListenerOld = new GpsStatus.NmeaListener() {
@Override
public void onNmeaReceived(long l, String nmea) {
receivedNmea(nmea);
}
};
}
locationManager.addNmeaListener(nmeaListenerOld);
}
}
Android 10 中的隐私权变更
在后台运行时访问设备位置信息需要权限 为了让用户更好地控制应用对位置信息的访问权限,Android 10 引入了 ACCESS_BACKGROUND_LOCATION 权限。
与 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION
权限不同,ACCESS_BACKGROUND_LOCATION 权限仅会影响应用在后台运行时对位置信息的访问权限。