代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

是否可以在Android O及以上版本中动态调整通知音量?

  •  9
  • Cheok Yan Cheng  · 技术社区  · 6 年前

    我完全理解,自从Android O及以上版本以来,并没有简单的方法通过应用程序的代码定制通知声音。

    通常的方法是调用 Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS

    private void showNotificationSoundListPreferenceDialogFragmentCompat(Preference preference) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, getContext().getPackageName());
            intent.putExtra(Settings.EXTRA_CHANNEL_ID, com.yocto.wenote.reminder.Utils.createNotificationChannel());
            try {
                startActivity(intent);
            } catch (android.content.ActivityNotFoundException e) {
                Log.e(TAG, "", e);
                trackEvent("showNotificationSoundListPreferenceDialogFragmentCompat", "fatal", e.getMessage());
            }
        }
    }
    

    看起来像是

    enter image description here

    然而,我注意到市场上的一些应用程序确实提供了动态调整通知音量的方法。

    enter image description here

    我想知道,实现这一目标的途径是什么?

    2 回复  |  直到 6 年前
        1
  •  4
  •   0xA Farid Haq    6 年前

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "Channel1");
    
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
        // Vibrations
    
        Vibrator vib = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vib.vibrate(VibrationEffect.createWaveform(new long[] {200,300,500,100,100}, 1));
    
        //Sound 
    
        Intent soundIntent = new Intent(this, PlaySound.class);
        serviceIntent.setAction("ACTION_START_PLAYBACK");
        serviceIntent.putExtra("UriSound", soundUri.toString());
        context.startForegroundService(soundIntent);
    
        // if notification is outted, just delete notification; thus delete intent
    
        Intent outNotification = new Intent(context, PlaySound.class);
        deleteIntent.setAction("ACTION_STOP_PLAYBACK");
        PendingIntent pendingOutNotification =
                PendingIntent.getService(this, 0, outNotification, 0);
        builder.setDeleteIntent(pendingOutNotification);
    
    } else {
    
        builder.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        builder.setSound(uri);
    
    }
    
    notificationManager.notify(0, builder.build());
    

    在你的 PlaySound.class extend service ,在电视上播放你的声音 media player ,并根据 intent 关于那一点 channel

    根据用户从滑块输入的内容,以卷或uri为目标,然后通过 意图 或者使用 sharedpreference s

        2
  •  2
  •   Vanshaj Daga    6 年前

    您可以通过以下步骤实现这一点 检查是否有适当的权限

    isNotificationPolicyAccessGranted()
    

    它需要安卓N以后,因为它可以修复“请勿打扰” 如果未提供,请明确请求许可

    Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS
    

    创建一个带有滑块的自定义视图,以获取介于

    然后用

    setStreamVolume(5, yourdesiredvalue in int , 0)