【问题标题】:Create silent notification [duplicate]创建静默通知[重复]
【发布时间】:2020-04-14 18:35:21
【问题描述】:

我有创建通知的功能。每次格式化通知时,它都会播放声音。是否可以创建不播放声音的静音通知?如何实现?

public void sendNotification(String title, String message,boolean playSound) {


        int NOTIFICATION_ID = 234;
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String CHANNEL_ID = "my_channel_01";

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
        {
            CharSequence name = "my_channel";
            String Description = "This is my channel";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            mChannel.setDescription(Description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mChannel.setShowBadge(false);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message);


        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        builder.setContentIntent(intent);



        Intent resultIntent = new Intent(this, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);

        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

【问题讨论】:

    标签: android android-studio


    【解决方案1】:

    除了使用

    NotificationManager.IMPORTANCE_HIGH 
    

    使用

    NotificationManager.IMPORTANCE_LOW
    

    Android 7 以下的设备需要使用 PRIORITY_LOW,Android 8 及以上的设备需要使用 IMPORTANCE_LOW。

    您也可以在 NotificationChannel(mChannel) 上使用 setSound(null, null) 方法

    【讨论】:

    • 还要考虑到你不能修改通知频道一旦创建(除了卸载应用程序)。所以也许考虑有两个通知通道,一个是静音的,一个是声音的
    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2016-09-30
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多