Java android 8(oreo)下的服务意外停止
我在谷歌Play商店编写并发布了一个应用程序(“传感器录制”)。它是关于读取传感器数据(如位置、加速度计、陀螺仪等),以数字或图形方式显示它们,并将它们存储到kml和csv文件中以供进一步处理,例如使用Google Earth或MS Excel。我已经建立了一个服务,在后台读取和处理数据,即使屏幕关闭 在安卓8之前,一切都运转良好。但在Oreo中,操作系统会在屏幕关闭约5分钟后自动停止服务。这是谷歌为了节省电池寿命而有意引入的。我在互联网上找到了一些应该避免这种情况的措施,但到目前为止没有任何效果 我所做的: 1.)在调用活动中,我将Java android 8(oreo)下的服务意外停止,java,android,service,Java,Android,Service,我在谷歌Play商店编写并发布了一个应用程序(“传感器录制”)。它是关于读取传感器数据(如位置、加速度计、陀螺仪等),以数字或图形方式显示它们,并将它们存储到kml和csv文件中以供进一步处理,例如使用Google Earth或MS Excel。我已经建立了一个服务,在后台读取和处理数据,即使屏幕关闭 在安卓8之前,一切都运转良好。但在Oreo中,操作系统会在屏幕关闭约5分钟后自动停止服务。这是谷歌为了节省电池寿命而有意引入的。我在互联网上找到了一些应该避免这种情况的措施,但到目前为止没有任何效
startService()
替换为startForegroundService()
2.)在服务本身中,我根据找到的提示在onStartCommand()
中进行了一些修改
使用wakeLock进行的测试也没有结果。如有任何进一步的想法,我们将不胜感激
private NotificationManager notMan;
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// show notification + startForeground
int id = 42;
String channelId = "42";
String text = "Sensors active";
Intent notificationIntent = new Intent(this, SensorService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel(channelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_DEFAULT);
notMan = getSystemService(NotificationManager.class);
notMan.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(this, channelId);
builder.setSmallIcon(R.drawable.vector3d_bg_transp)
.setContentTitle("Sensor Service")
.setContentText(text)
.setTicker(text)
.setSubText("Start Service")
.setShowWhen(true);
notification = builder.build();
}
else
{
notMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.vector3d_bg_transp)
.setContentTitle("Sensor Service")
.setContentText(text)
.setTicker(text)
.setSubText("Start Service")
.setPriority(PRIORITY_DEFAULT)
.setShowWhen(true).build();
}
startForeground(id, notification);
return super.onStartCommand(intent, flags, startId); // = 1, same as START_STICKY
} // onStartCommand
最近,我找到了解决方案——在Thomas Künneth(各种Android书籍的作者)的一个重要提示之后。补救办法不在源代码中,而是在智能手机的设置中。有一个选项可以启用后台处理。在我的带有Android 8.0的华为P10 Lite上,它位于以下菜单树中(可能其他设备或Android版本也有类似的选项):
- 背景
- 电池组
- 发射
- 选择有问题的应用程序
- 将“自动管理”切换为“手动管理”
- 在弹出菜单中设置开关“在后台运行”
值得注意的是,谷歌提供了这个选项,但在关于安卓8的讲座中并没有强调它。当然,这与新政策“电池优先”是一致的。您的目标是api 28吗?如果是这样,您必须请求前台服务许可证编号!targetSdkVersion 26,compileSdkVersion 26,minSdkVersion 14这不是谷歌的做法。这是华为的做法。股票安卓8.1(在Nexus 5X和配备安卓系统的诺基亚3.1上进行测试)没有“发布”选项。