常驻通知栏的设计与实现

通知栏的创建

在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;
    }

  • Android 8.0版本及以后的创建方式:
 /**
     * 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);
  • 开启一个service并且调用startForeground方法,可以提升app的存活率
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/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容