Android启动前台服务startForegroundService的正确方式

7. startForegroundService 报错

E AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{990dd99 u0 com.android.fmradio/.FmService}Android O中,有一个新的背景限制。尝试启动startService()时,将获得IlleagalStateException,因此现在应使用startForegroundService(),但是如果通过此新方法启动服务,则会在屏幕截图中看到类似的错误。为避免此异常,您需要在startForegroundService()之后有5秒钟的时间来创建startForeground(),以通知用户您正在后台工作。否则将崩溃出现这样的崩溃信息
    
1. 启动服务,适配启动方案
//适配8.0以上的服务转前台服务 清单文件AndroidManifest中有配置 android.permission.FOREGROUND_SERVICE
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    //适配8.0机制
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

2. service服务中的onCreate()中加上如下代码
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { // 注意notification也要适配Android 8 哦
    startForeground(ID, new Notification());// 通知栏标识符 前台进程对象唯一ID
}

===
NotificationManager notificationManager = (NotificationManager) 
 getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, "诺秒贷", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(1, notification);
        }
===
    
3.另外在9.0的系统上需要添加权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
类别 区别 应用
前台服务 会在通知一栏显示 ONGOING 的 Notification, 当服务被终止的时候,通知一栏的 Notification 也会消失,这样对于用户有一定的通知作用。 常见的如音乐播放服务
后台服务 默认的服务即为后台服务,即不会在通知一栏显示 ONGOING 的 Notification。 当服务被终止的时候,用户是看不到效果的。 某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等。

启动一个前台服务要做的事情有:

 (1) 调用 ContextCompat.startForegroundService() 可以创建一个前台服务,相当于创建一个后台服务并将它推到前台;

 (2)  创建一个用户可见的 Notification ;

 (3)  必须在5秒内调用该服务的 startForeground(int id, Notification notification) 方法,否则将停止服务并抛出 android.app.RemoteServiceException:Context.startForegroundService() did not then call Service.startForeground()异常。
 
- 如果在 5 秒内没有调用startForeground(),timeout 就会触发,会报出ANR 
-  一旦通过startForegroundService() 启动前台服务,必须在service 中有startForeground() 配套,不然会出现ANR 或者crash
- startForeground() 中的id 和notification 不能为0 和 null

你可能感兴趣的:(Android,android,service,notification,anr)