美文网首页
Android学习笔记之Notification

Android学习笔记之Notification

作者: sssssss_ | 来源:发表于2021-11-03 11:57 被阅读0次

    一、需求

    • 自定义通知栏
    • 适配 Android 8.0
    • 按钮点击事件

    二、代码

    2.1 通知栏的代码

    /**
     * 构造通知栏参数
     */
    private void createNotificationConfig() {
        String ID = "xxx";    //这里的 id 里面输入自己的项目的包的路径
        String NAME = "xxx"; // 用于 channel 的名称
    
        // 获取通知的实例
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder notificationBuilder; //创建服务对象
        // 判断版本,当大于Android 8.0时,需要创建通知渠道 channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            manager.createNotificationChannel(channel);
            notificationBuilder = new NotificationCompat.Builder(TrackService.this).setChannelId(ID);
        } else {
            notificationBuilder = new NotificationCompat.Builder(TrackService.this);
        }
        // 使用Builder构造一个notification对象
        notificationBuilder.setContent(getRemoteView())
                .setOngoing(true)
                .setWhen(System.currentTimeMillis()) // 设置通知被创建的时间
                .setSmallIcon(R.drawable.ic_svg_stop_track) // 小图标
                .setTicker("通知来了")
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(PendingIntent.getBroadcast(this, 2,
                        new Intent("android.songsong.view"), PendingIntent.FLAG_UPDATE_CURRENT));
        manager.notify(100, notificationBuilder.build());
    
    

    2.2 自定义通知栏样式

    /**
     * 构建自定义通知栏的样式
     * @return RemoteViews
     */
    private RemoteViews getRemoteView() {
        RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.notification_track_record_view);
        remoteView.setTextViewText(R.id.notification_title_id, "songsong");
        remoteView.setTextViewText(R.id.notification_track_id, "songsong-track");
        remoteView.setOnClickPendingIntent(R.id.notification_track_stop_id,
                getBroadcastStopPendingIntent(11)); // 点击事件的意图
        remoteView.setOnClickPendingIntent(R.id.notification_layout,
                getTrackActivityPendingIntent(12)); // 点击事件的意图
        return remoteView;
    }
    /**
     * 构建 点击按钮返回的事件
     * @param what 标记符
     * @return PendingIntent
     */
    private PendingIntent getBroadcastStopPendingIntent(int what) {
        Intent i = new Intent("android.songsong.stop");
        PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, what, i, PendingIntent.FLAG_UPDATE_CURRENT);
        return stopPendingIntent;
    }
    /**
     * 构建点击layout返回的事件
     * @param what
     * @return
     */
    private PendingIntent getTrackActivityPendingIntent(int what) {
        Intent i = new Intent("android.songsong.view");
        PendingIntent actionPendingIntent = PendingIntent.getBroadcast(this, what, i, PendingIntent.FLAG_UPDATE_CURRENT);
        return actionPendingIntent;
    }
    

    2.3 广播监听器

    onCreate() 中执行 registerReceiver(this) 广播的注册

    /**
     * 注册广播
     * @param context
     */
    private void registerReceiver(Context context) {
        if (mMyBroadcastReceiver == null) {
            mMyBroadcastReceiver = new MyBroadcastReceiver();
        }
        if (mIntentFilterStop == null) {
            mIntentFilterStop = new IntentFilter("android.songsong.stop");
        }
        if (mIntentFilterView == null) {
            mIntentFilterView = new IntentFilter("android.songsong.view");
        }
        registerReceiver(mMyBroadcastReceiver, mIntentFilterStop);
        registerReceiver(mMyBroadcastReceiver, mIntentFilterView);
    }
    /**
     * 广播接收器
     */
    class MyBroadcastReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            collapseStatusBar(context);
            if (action.equals("android.songsong.stop")) {
                L.v("SONGSONG");
            }
        }
    }
    
    // 需要申请权限
    <uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>
    
    /**
     * 收起通知栏
     * @param context
     */
    public void collapseStatusBar(Context context) {
        try {
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
    

    三、参考文章

    相关文章

      网友评论

          本文标题:Android学习笔记之Notification

          本文链接:https://www.haomeiwen.com/subject/pcwqzltx.html