当我的应用程序在后台时调用 onLocationChanged 太晚了
onLocationChanged is called too late when my App is in background
我正在获取服务中的位置更新。当我的应用程序处于前台时,OnLocationChange 在几秒钟内被调用。但是当它在后台时,它会在几分钟后被调用.. 问题是什么?什么是解决方案?
我在后台运行时不会停止我的服务。
我发现了问题。 Android 从 8.0 开始对位置更新添加了限制 here:
"In an effort to reduce power consumption, Android 8.0 (API level 26) limits how frequently background apps can retrieve the user's current location. Apps can receive location updates only a few times each hour."
解决方法:需要启动Foreground Service,需要显示通知,如:
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);
我正在获取服务中的位置更新。当我的应用程序处于前台时,OnLocationChange 在几秒钟内被调用。但是当它在后台时,它会在几分钟后被调用.. 问题是什么?什么是解决方案? 我在后台运行时不会停止我的服务。
我发现了问题。 Android 从 8.0 开始对位置更新添加了限制 here:
"In an effort to reduce power consumption, Android 8.0 (API level 26) limits how frequently background apps can retrieve the user's current location. Apps can receive location updates only a few times each hour."
解决方法:需要启动Foreground Service,需要显示通知,如:
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);