常驻通知栏的设计与实现

2022-10-07  本文已影响0人  放羊娃华振

通知栏的创建

在Android设备上如果要实现通知栏功能,需要区分系统版本,因为大于等于Android 8.0系统的和之前版本使用的方式不一致,故需要加版本区分代码:

//构建通知栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {  //8.0
            createApi26();
        } else {
            createNormal();
        }
    /**
     * 创建8.0以下的ui
     */
    @SuppressWarnings("all")
    private void createNormal() {
        if (mBuilder == null) {
            mBuilder = new NotificationCompat.Builder(mContext);
        }
        if (notification != null) {
            notification = null;
        }
        mBuilder
//                .setContent(mNormalRemoteViews)
                .setCustomContentView(mSmallNormalRemoteViews)
                .setCustomBigContentView(mNormalRemoteViews)
                .setSmallIcon(R.drawable.ic_launcher)
                .setPriority(Notification.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);
        notification = mBuilder.build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
    }

 /**
     * 8.0以上创建通知栏
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createApi26() {
        if (manager == null) return;
        if (mChannel == null) {
            mChannel = new NotificationChannel(mChannelId, mChannelName,
                    NotificationManager.IMPORTANCE_HIGH);
        }
        manager.createNotificationChannel(mChannel);
        if (notification != null) {
            notification = null;
        }
        notification = new NotificationCompat.Builder(mContext, mChannelId)
//                .setContent(mNormalRemoteViews)
                .setCustomContentView(mSmallNormalRemoteViews)
                .setCustomBigContentView(mNormalRemoteViews)
                .setShowWhen(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT;

    }
//展示通知栏
manager.notify(notifycatonid, notification);
//取消通知栏
manager.cancel(notifycatonid);
startForeground(NOTICE_ID, notification);

意外看到别人的文章也就收集着吧:
http://hoyoshaw.github.io/2015/12/15/%E9%80%9A%E7%9F%A5%E7%AE%A1%E7%90%86%E5%8A%9F%E8%83%BD%E4%B8%8E%E5%B8%B8%E9%A9%BB%E9%80%9A%E7%9F%A5%E6%A0%8F%E7%9A%84%E8%AE%BE%E8%AE%A1%E4%B8%8E%E5%AE%9E%E7%8E%B0/

上一篇 下一篇

猜你喜欢

热点阅读