繁体   English   中英

服务在 android 8 (oreo) 下意外停止

[英]service stops unexpectedly under android 8 (oreo)

我在 Google Play 商店编写并发布了一个应用程序(“传感器录音”)。 它是关于读取传感器数据(例如位置、加速度计、陀螺仪等),以数字或图形方式显示它们并将它们存储到 kml 和 csv 文件中以供进一步处理,例如使用 Google Earth 或 MS Excel。 我已经建立了一项服务,即使屏幕关闭,也可以在后台读取和处理数据。

一切正常,直到 Android 8。但在 Oreo 中,操作系统会自动停止该服务,大约。 屏幕关闭后 5 分钟。 这是谷歌有意引入的,以节省电池寿命。 我在互联网上找到了一些应该避免这种情况的措施,但到目前为止没有任何效果。

我做了什么:

1.) 在调用活动中,我用startForegroundService()替换了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 版本也有类似的选项):

  • 设置
  • 电池
  • 发射
  • 选择有问题的应用程序。
  • 将开关从“自动管理”设置为“手动管理”。
  • 在弹出菜单中设置开关“在后台运行”。

就是这样,很简单——如果你知道怎么做的话。

值得注意的是,谷歌提供了这个选项,但在关于Android 8的讲座中并没有强调它。当然,这与“电池优先”的新政策是一致的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM