In my app I have bundled a custom unique sound for push notifications with FirebaseMessagingService.
I have also built in the ability for the user to choose their own custom sound.
With the below code if the use IS IN THE APP: the user chosen sound will play if they chose one. BUT if out of the application, my custom unique sound will play.
I would like for the users selected custom notification sound (if they chose one) to play if they are not using the app instead of my unique sound.
I have stored the Ringtone sound URI in a preferences file: content://media/internal/audio/media/57
public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCMService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(final String messageBody) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = null;
if (AppPref.getUserWantsCustomSound()){
//ANDROID SOUND CHOSEN BY USER
defaultSoundUri = Uri.parse(AppPref.getUserCustomSound()); // Returns content://media/internal/audio/media/57
} else {
//PRE PACKAGED SOUND included in app
defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pushnotify);
}
Log.d(TAG, "defaultSoundUri: " + defaultSoundUri);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My App")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
//IF IN APP SHOW A TOAST MESSAGE
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),messageBody,Toast.LENGTH_SHORT).show();
}
});
}
}