notification only play default sound not the custom sound which I set in notification in android

20 views Asked by At
enter code here

public class NotificationDemo extends AppCompatActivity {

Button btn;
private static final String CHANNEL_ID = "My Channel";
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;

Uri soundUri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.instrument);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_demo);

    btn = findViewById(R.id.btnNoti);

    AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

    btn.setOnClickListener(view -> {



        Intent intent = new Intent(this, NotificationDemo.class);
        PendingIntent intent1;

        intent1 = PendingIntent.getActivities(this, 0, new Intent[]{intent}, PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotificationDemo.this, CHANNEL_ID)
                .setSmallIcon(R.drawable.email)
                .setContentTitle("Test Title")
                .setContentText("This is Simple notification")
                .setSound(soundUri)
                .setContentIntent(intent1);


        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE );

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

            int importance = NotificationManager. IMPORTANCE_HIGH ;
            NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
            notificationChannel.enableLights( true ) ;
            notificationChannel.setLightColor(Color. RED ) ;

            notificationChannel.setSound(soundUri,audioAttributes) ;
            mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID) ;
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel) ;
        }
        assert mNotificationManager != null;
        mNotificationManager.notify(( int ) System. currentTimeMillis () ,
                mBuilder.build()) ;

    });

}

}

** I run the code but only the phone default sound is playing not the sound which I set.

-> I also check the logcat but no error showing there

-> If anyone know the answer of this it would be great help for me.

**

0

There are 0 answers