Android 8.0 通知栏的适配

完整代码如下

package ai.aitek.cattserver

import ai.aitek.gattserver.R
import android.app.*
import android.content.Intent
import android.os.IBinder
import android.os.Build
import android.support.v4.app.NotificationCompat
import java.util.*


class ForegroundService : Service() {
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        val pendingIntent = PendingIntent.getActivity(applicationContext,
                0,
                Intent(applicationContext, GattServerActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT);//这里第二个参数可以用于后边根据不同的消息设置不同的点击事件

        var mBuilder: NotificationCompat.Builder? = null

        val notificationManager = applicationContext.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= 26) {
            val channel = NotificationChannel("YOUR_CHANNEL_ID001", "YOUR_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)

            mBuilder = NotificationCompat.Builder(applicationContext, "YOUR_CHANNEL_ID001")

        } else {
            mBuilder = NotificationCompat.Builder(applicationContext);
        }
        mBuilder.setContentTitle("GattServer标题")//设置通知栏标题  
                .setContentText("GattServer内容")//设置通知栏显示内容
//                            .setContent(contentViews)
//                            .setNumber(20)//设置通知集合的数量  
                .setTicker("通知来啦")//通知首次出现在通知栏,带上升动画效果的  
                .setWhen(System.currentTimeMillis())//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间  
                .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级  
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消    
                .setOngoing(false)//true,设置他为一个正在进行的通知  
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单
        //设置通知小ICON  
        try {
            mBuilder.setSmallIcon(R.mipmap.cattserver);
        } catch (e: Exception) {
            e.printStackTrace();
        }

        mBuilder.setContentIntent(pendingIntent);
        notificationManager.notify(UUID.randomUUID().hashCode(), mBuilder.build());

        return super.onStartCommand(intent, flags, startId);
    }
}

不适配的话会报以下错误


android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification

你可能感兴趣的:(Android 8.0 通知栏的适配)