Android 8经过startService引发crash问题

Android 8.0 再也不容许后台service直接经过startService方式去启动,不然就会引发IllegalStateException。解决方式:java

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, MyService.class)); } else { context.startService(new Intent(context, MyService.class));
}

 

而后必须在Myservice中调用startForeground():缓存

@Override
public void onCreate() { super.onCreate(); startForeground(1,new Notification()); }

 注意:在要开启的service中给notification添加 channelId,不然会出现以下错误:ide

RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid ch......函数

完整参考代码以下:性能

 

    NotificationManager notificationManager;  ui

    String notificationId = "channelId";    this

    String notificationName = "channelName";    spa

    private void startForegroundService().net

    {        code

       notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        

      //建立NotificationChannel        

      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            

      NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);            

      notificationManager.createNotificationChannel(channel);       

      }        

      startForeground(1,getNotification());    

  }

  private Notification getNotification() {        

    Notification.Builder builder = new Notification.Builder(this)

                 .setSmallIcon(R.drawable.myicon)

                 .setContentTitle("投屏服务")

                 .setContentText("投屏服务正在运行...");   

      //设置Notification的ChannelID,不然不能正常显示        

     if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {            

        builder.setChannelId(notificationId);        

     }        

    Notification notification = builder.build();        

    return notification;    

  }    

  @Override  

  public void onCreate() {        

    super.onCreate();       

    startForegroundService();   

    FLog.d(TAG, "[onCreate] MediaServer Service Started.");    

  }

 

补充:关于Android 8.0中Service和Notification

后台执行限制 Android 8.0 为提升电池续航时间而引入的变动之一是,当您的应用进入已缓存状态时,若是没有活动的组件,系统将解除应用具备的全部>>>唤醒锁。 此外,为提升设备性能,系统会限制未在前台运行的应用的某些行为。具体而言: 如今,在后台运行的应用对后台服务的访问受到限制。 应用没法使用其清单注册大部分隐式广播(即,并不是专门针对此应用的广播)。 默认状况下,这些限制仅适用于针对 O 的应用。不过,用户能够从 Settings 屏幕为任意应用启用这些限制,即便应用并非以 O 为目标平台。 Android 8.0 还对特定函数作出了如下变动: 若是针对 Android 8.0 的应用尝试在不容许其建立后台服务的状况下使用 startService() 函数,则该函数将引起一个 IllegalStateException。 新的 Context.startForegroundService() 函数将启动一个前台服务。如今,即便应用在后台运行,系统也容许其调用 Context.startForegroundService()。不过,应用必须在建立服务后的五秒内调用该服务的 startForeground() 函数。

参考连接:

https://blog.csdn.net/huaheshangxo/article/details/82856388

相关文章
相关标签/搜索