如何在Android中添加自定义通知声音

帕蒂·巴亚尼

我必须管理通知,为此,我需要管理自定义声音。那么您是否知道我们如何做到这一点?

我已经将声音文件复制到我的原始文件夹中,因此任何人都对如何将其实现到我的项目有任何想法。

提前致谢。

拉文德拉·库什瓦哈(Ravindra Kushwaha)

首先,将“资源(res)”中的文件夹命名为原始文件夹,然后将文件(YOUR_SOUND_FILE.MP3)放入其中,然后使用下面的代码行自定义声音

   NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context,
            SlidingMenuActivity.class);
    notificationIntent.putExtra("isInbox", true);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

将这些代码行用于自定义声音

 notification.sound =Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play


    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);

编辑更新

对于奥利奥和更高的,你需要检查SDK_VERSION和使用setSound的方法NotificationChannel

Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.FILE_NAME);  //Here is FILE_NAME is the name of file that you want to play

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
                "YOUR CHANNEL NAME",
                NotificationManager.IMPORTANCE_DEFAULT)

            AudioAttributes attributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, 
                    context.getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            mChannel.setDescription(msg);
            mChannel.enableLights(true);
            mChannel.enableVibration(true);
            mChannel.setSound(sound, attributes); // This is IMPORTANT


            if (mNotificationManager != null)
                mNotificationManager.createNotificationChannel(mChannel);
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章