首页 > 解决方案 > 服务在 android 8 (oreo) 下意外停止

问题描述

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

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

我做了什么:

1.)在我已替换为的调用活动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

标签: javaandroidservice

解决方案



推荐阅读