Android 8.0通知栏推送及适配

上一篇我们确保了我们开启了通知栏的权限,那么接下来就是发送推送了,废话不多说,上代码。

首先我们判断手机版本号,Android版本大于8.0的时候呢,我们需要进行一下通道的操作才可:判断版本号代码接好

//此处判断安卓版本号是否大于或者等于Android8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "chat";//设置通道的唯一ID
    String channelName = "聊天消息";//设置通道名
    int importance = NotificationManager.IMPORTANCE_HIGH;//设置通道优先级
    createNotificationChannel(channelId, channelName, importance,title,text);
} else {
    sendSubscribeMsg(title,text);
}

Android8.0+适配

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance,String title,String text) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) AppApplication.getContext().getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
        sendSubscribeMsg(title,text);
    }

通知栏推送代码

public void sendSubscribeMsg(String title,String text) {
    NotificationManager manager = (NotificationManager) AppApplication.getContext().getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new NotificationCompat.Builder(AppApplication.getContext(), "chat")
            .setContentTitle(title)
            .setContentText(text)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.logo)
            .setLargeIcon(BitmapFactory.decodeResource(AppApplication.getContext().getResources(), R.mipmap.logo))
            .setAutoCancel(true)
            .build();
        manager.notify(2, notification);
    }

我们还可以给notification设置其他属性,例如:

setCustomContentView(createContentView())  用于设置自定义的View
notification.flags |= Notification.FLAG_NO_CLEAR; 设置flags 使其无法被滑动删除

你可能感兴趣的:(开发,安卓)