Android notification setSound is not working

后端 未结 8 1626
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 04:46

In my hybrid Cordova Android app targeting API 23+ I want to use a custom sound for notifications. To that end I have done the following

  • In plugin.xml
8条回答
  •  暖寄归人
    2021-02-01 04:53

    below code will help you:

     String CHANNEL_ID="1234";
    
        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.mysound);
        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 
    
      //For API 26+ you need to put some additional code like below:
        NotificationChannel mChannel;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                    mChannel.setLightColor(Color.GRAY);
                    mChannel.enableLights(true);
                    mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build();
                    mChannel.setSound(soundUri, audioAttributes);
    
                    if (mNotificationManager != null) {
                        mNotificationManager.createNotificationChannel( mChannel );
                    }
            }
    
       //General code:
         NotificationCompat.Builder status = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);     
                              status.setAutoCancel(true)
                                    .setWhen(System.currentTimeMillis())
                                    .setSmallIcon(R.drawable.logo)
                                    //.setOnlyAlertOnce(true)
                                    .setContentTitle(getString(R.string.app_name))
                                    .setContentText(messageBody)
                                    .setVibrate(new long[]{0, 500, 1000})
                                    .setDefaults(Notification.DEFAULT_LIGHTS )
                                    .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +mContext.getPackageName()+"/"+R.raw.apple_ring))
                                    .setContentIntent(pendingIntent)
                                    .setContent(views);
    
                            mNotificationManager.notify(major_id, status.build());
    

    where mysound is my ringtone which is put under res/raw folder.

    Note: you have to only put name of ringtone without extension like raw/mysound

提交回复
热议问题