当前位置: 代码迷 >> 综合 >> Android 8.0 后台Service限制
  详细解决方案

Android 8.0 后台Service限制

热度:69   发布时间:2023-10-18 18:10:44.0

Android O 后台启动Service崩溃问题

  • 在 Android 8.0 (API26)之前,创建前台服务的方式通常是先创建一个后台服务,然后将该服务推到前台。
  • Android 8.0 (API26)有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。
  • 在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。
  • 如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

 

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

解决方法

  • 将 调用 startService启动Service 改为调用 startForegroundService

 

public static void start() {Intent intent = new Intent(AppContext.me(), ScoreRefreshServer.class);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {AppContext.me().startForegroundService(intent);} else {AppContext.me().startService(intent);}
}
  • 在service的onCreate方法中调用startForeground()

 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//NotificationCompat.Builder builder =//new NotificationCompat.Builder(this, CHANNEL_ID)//         .setContentTitle("")//         .setContentText("");NotificationChannel channel = new NotificationChannel(AppEnv.UMENG_CHANNEL, getString(R.string.yoyo_name), NotificationManager.IMPORTANCE_MIN);channel.enableVibration(false);//去除振动NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);if (manager != null) manager.createNotificationChannel(channel);Notification.Builder builder = new Notification.Builder(getApplicationContext(), AppEnv.UMENG_CHANNEL)
//                    .setContentTitle("正在后台运行").setSmallIcon(R.mipmap.logo);startForeground(1, builder.build());//id must not be 0,即禁止是0
}



 

  相关解决方案