1、在Manifest.xml文件中application标签中添加Service声明
<!-- 前台Service的方式来提高进程级别,使定位服务由后台转向前台-->
<service android:name="com.tencent.map.geolocation.s" android:foregroundServiceType="location"/>
注册申请权限,允许在后台获取权限
<!-- Android Q新增权限,允许应用在后台发起定位,如应用target为Q,请添加此权限 -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
2、在Acivity中,申请要求权限,需同意始终获取定位,不然后台定位不起作用
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestPermission() {
String[] permissions = onRequestPermissions();
if (permissions != null) {
List<String> deniedPermissions = new ArrayList<>();
for (String permission : permissions) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
deniedPermissions.add(permission);
}
}
if (deniedPermissions.size() > 0) {
requestPermissions(deniedPermissions.toArray(new String[0]), PERMISSIONS_REQUEST_CODE);
}
}
}
protected String[] onRequestPermissions() {
return new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
}
3、在启动定位之前,调用enableForegroundLocation,如下:
mLocationManager.enableForegroundLocation(LOC_NOTIFICATIONID, buildNotification());
mLocationManager.requestLocationUpdates(request, this, getMainLooper());
构建Notification
private Notification buildNotification() {
Notification.Builder builder = null;
Notification notification = null;
if (android.os.Build.VERSION.SDK_INT >= 26) {
//Android O上对Notification进行了修改,如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
String channelId = getPackageName();
if (!isCreateChannel) {NotificationChannel notificationChannel = new NotificationChannel(channelId,
NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
notificationManager.createNotificationChannel(notificationChannel);
isCreateChannel = true;
}
builder = new Notification.Builder(getApplicationContext(), channelId);
} else {
builder = new Notification.Builder(getApplicationContext());
}
builder.setContentTitle("LocationDemo")
.setContentText("正在后台运行")
.setWhen(System.currentTimeMillis());
if (android.os.Build.VERSION.SDK_INT >= 16) {
notification = builder.build();
} else {
notification = builder.getNotification();
}
return notification;
}
4、停止定位后,调用disableForegroundLocation停止前台服务,关闭后台定位
LocationManager.removeUpdates(this);
mLocationManager.disableForegroundLocation(true);
腾讯官方文档 定位Demo
|