[英]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.