java - 服务在 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
解决方案
推荐阅读
- java - 密码密码分析实现
- node.js - React App 和 Express API 的单一可执行文件
- oracle - 删除前触发
- tensorflow - 余弦相似度损失导致权重值爆炸
- java - 使用输出流增加文件大小
- php - 在现有表中添加列而不使用 Laravel 中的迁移
- php - 用ajax调用函数url页面
- c++ - tgbot-cpp - 回答内联查询
- javascript - 当我尝试访问我查询的文档元素时,Mongoose 返回 undefined
- android - com.parse.fcm.ParseFirebaseInstanceIdService' 不可分配给 'android.app.Service'