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

标签 android

我完全理解自 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

请问有什么方法可以实现?

最佳答案

这只是一种 hack,一种让它这样做的方法,它将实现您所需的行为。在我的应用程序中,目标是 API 26;我已经实现了声音和振动定制,但手动进行。

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...

根据用户从 slider 输入的音量或 uri 定位,然后通过 intent 发送或使用 sharedpreference 将其保存在键值对中。

关于android - 是否可以在 Android O 及更高版本中动态调整通知音量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910653/

相关文章:

android - ExpandableListView中的SwipeListView,可以吗?

java - 在 Java 项目中放置文本文件的文件夹以及如何引用文件夹

android - 配置 'compile'已过时,已被 'implementation'和 'api'取代。有人可以帮我解决此错误吗?

Android Market Activity Intent - 未找到 Activity

java - 膨胀类 fragment 谷歌 API 时出错

android - 基于 play-services-base 的 google play 服务的用例

android - 如何让 Activity 在根据 Intent 切换到新布局之前等待?

android - android按钮和监听器。我怎样才能使它更短

android - 如何以编程方式修复android上的圆角按钮?

android - Android Studio-如何使用Gradle将资源文件包含在Java包中