因此,对于 Android O,如果您希望每小时接收的不仅仅是几次位置更新,您需要将服务作为前台服务运行。
我注意到启动前台服务的旧方法似乎确实适用于 O。
IE。
startForeground(NOTIFICATION_ID, getNotification());
根据此处的行为改变指南:https://developer.android.com/preview/behavior-changes.html
NotificationManager.startServiceInForeground() 方法启动前台服务。启动前台服务的旧方法不再有效。
虽然新方法仅在针对 O 时有效,但无论是否针对 O,旧方法似乎仍然适用于 O 设备。
Edit包括示例:
Google 示例项目 LocationUpdatesForegroundService 实际上有一个工作示例,您可以在其中直接看到该问题。https://github.com/googlesamples/android-play-location/tree/master/LocationUpdatesForegroundService
无论是针对 API 级别 25 进行定位和编译,还是针对 O 进行定位和编译,startForeground 方法似乎都可以正常工作(如下所示:https://developer.android.com/preview/migration.html#uya)
因此,重现:
- 按照上一个链接中所述配置应用程序 gradle
- 打开应用程序
- 请求位置更新
- 关闭应用程序(通过后退按钮或主页按钮)
服务正在前台运行(由通知栏中的图标显示)。即使在运行 O 的设备上,位置更新也会按预期进行(每 10 秒一次)。我在这里缺少什么?
这对我有用。
- 在 Activity 类中,使用启动服务启动前台服务()代替启动服务()
Intent myService = new Intent(this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(myService);
} else {
startService(myService);
}
- 现在在服务舱onStartCommand()执行以下操作
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
......
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText(text)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(1, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(1, notification);
}
return START_NOT_STICKY;
}
注意:使用通知生成器代替通知兼容生成器让它发挥作用。仅在Notification.Builder中,您需要提供Channel ID,这是Android Oreo中的新功能。
希望它有效!
EDIT:
如果您的目标 API 级别为 28 或更高,则需要 FOREGROUND_SERVICE 权限,否则您的应用程序将崩溃。
只需将其添加到 AndroidManifest.xml 文件中即可。
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)