Android Notification的使用

本文展示了如何在AndroidManifest.xml中添加POST_NOTIFICATIONS权限,以及在Android8.0及以上版本创建和管理通知通道,包括设置通知的振动模式、重要性和颜色。同时,代码检查并处理了通知的开启状态,引导用户到通知设置页面进行调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

常用通知的写法,兼容android 8.0之后的版本

    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title) {
        //这里点击通知跳转的以MainActivity为例
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        CharSequence name = "test";
        String description = "test_description";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("test1", name, importance);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{0, 1000, 1000, 1000});
        NotificationManager manager = getNotificationManager();
        Notification.Builder notification = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText("this is content text 123456789")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .setLights(Color.GREEN, 1000, 1000)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//26,android 8.0
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
            notification.setChannelId("test1")
        }
        //如果涉及前台服务startForegroundService方式调用通知,且SDK版本大于31 
        //那么需要加上这个setForegroundServiceBehavior
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//            notification.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
//       }

        //跳转通知管理页
        boolean isNotifyEnable = NotificationManagerCompat.from(getApplicationContext()).areNotificationsEnabled();
        boolean isChannelEnable = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//26,android 8.0
            isChannelEnable = channel.getImportance() != NotificationManager.IMPORTANCE_NONE;
        }
        if (isNotifyEnable && isChannelEnable) {//发送通知,或者做一些操作,比如设置通知内容
            //manager.notify(1, notification);
            notification.setContentText("123456789");
        } else if (!isNotifyEnable) {
            Intent intent = new Intent();
            if (!(getApplicationContext() instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//26,android 8.0
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                getApplicationContext().startActivity(intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName()));
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//21,android 5.0
                intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
                getApplicationContext().startActivity(intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName()));
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {//9,android 2.3
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setData(Uri.fromParts("package", getPackageName(), null));
                getApplicationContext().startActivity(intent);
            } else {
                System.out.println("低于9没有适配必要");
            }
        } else {
            System.out.println("只打开了通知开关,但是关闭了当前channel的通知,开发者需要根据通知重要性,自行决定如何提示用户");
        }
        return notification.build();
    }
    
    //发送通知
    public void sendNotification(String title) {
        getNotificationManager().notify(1,getNotification(title));
    }

如果涉及前台服务startForegroundService方式调用通知,且SDK版本大于31 ,把代码中注释去掉即可。
例如:下面这段log就表示被原生逻辑拦截了导致通知没能及时显示

NotificationService: Notification Notification(channel=backup_nofitfy_channel shortcut=null contentView=null bigContentView=null vibrate=null sound=null tick defaults=0 flags=FOREGROUND_SERVICE color=0x00000000 vis=PRIVATE) is ForegroundServiceNotification, behavior is UPDATE_ONLY.

就需要Notification.Builder创建时setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值