Android 8通过startService引起crash问题

Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException。解决方式:

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,否则会出现如下错误:

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

完整参考代码如下:

 

    NotificationManager notificationManager;  

    String notificationId = "channelId";    

    String notificationName = "channelName";    

    private void startForegroundService()

    {        

       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

 

原文地址:https://www.cnblogs.com/wangqiang9/p/10595417.html