Custom Sound Not Playing Firebase Messaging Android - java

I am trying to use Custom Notification sound in my android application. I have checked all related questions and answers in stackoverflow but I am not able to figure why its not playing my custom sound in application. My code for notification is like below.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
}
if (remoteMessage.getData().size() > 0) {
sendNotification(remoteMessage.getData().get("title"));
}
}
#Override
public void onNewToken(String token) {
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Context context = getBaseContext();
String channelId = "raj";
int sound_notification = context.getSharedPreferences("setting", MODE_PRIVATE).getInt("sound_notification", 1);
Uri MyCustomSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/raw/sound" + (sound_notification));
//Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageBody)
.setAutoCancel(true)
.setSound(MyCustomSound)
.setContentIntent(pendingIntent);
//notificationBuilder.setSound(MyCustomSound);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Raj",
NotificationManager.IMPORTANCE_HIGH);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0, notificationBuilder.build());
}
}
I have tried to send notification from My Server with PHP as well from Firebase Console but its always play default sound instead my custom sound. Let me know if someone can help me for out from the issue.
Thanks

notification.sound = Uri.parse("android.resource://" + getPackageName() + "/sound/" + R.raw.sound);
mBuilder.setSound(Uri.parse("android.resource://" + getPackageName() + "/sound/" + R.raw.sound));

Related

Heads up notification not showing well in Samsung devices

I have been trying showing heads up notification as part of Full Screen Intent. It works well in some devices and if device is not locked, it shows up as heads up notification.
But in samsung devices, i have set system notification setting to brief (that shows notification for brief amount of time and then disappear back to system tray). This setting causing heads up notification to appear for small amount of time.
For the same setting, whatsapp and system caller app able to show heads up notification for incoming call.
i have used the following code
Channel creation
private void createFullIntentChannel(){
NotificationManager manager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3" ) ;
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
String NOTIFICATION_CHANNEL_ID = "com.myapp.app.fullintent";
String channelName = "FullRide";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.enableVibration(true);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(sound, attributes);
chan.setShowBadge(true);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(chan);
}
}
Setting content and action buttons on notification
public void showFullScreenIntent(final int notifId, String pickLoc, String dropLoc, String tripType, String accountID, String accountType,
String qrMode, Integer stopCount, Integer vhclType, String estInfo) {
setMediaPlayerFile();
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
PlayFile();
}
});
PlayFile();
}
// set content pending intent
Intent fullScreenIntent = new Intent(ctx, NewRideRequest.class);
fullScreenIntent.putExtra("Action", "UserChoice");
fullScreenIntent.putExtra("ID", notifId);
fullScreenIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent contentIntent = PendingIntent.getActivity(ctx, ACTION_USER_REQUEST_ID,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button accept pending intent
Intent acceptIntent = new Intent(ctx, NewRideRequest.class);
acceptIntent.putExtra("Action", "Accept");
acceptIntent.putExtra("ID", notifId);
acceptIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingAcceptIntent = PendingIntent
.getActivity(ctx, ACTION_INTENT_REQUEST_ID, acceptIntent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button reject pending intent
Intent rejectIntent = new Intent(ctx, NotificationAction.class);
rejectIntent.putExtra("Action", "Reject");
rejectIntent.putExtra("ID", notifId);
rejectIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingRejectIntent = PendingIntent
.getBroadcast(ctx, ACTION_INTENT_REQUEST_ID, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3") ;
createFullIntentChannel();
String val = dbHelper.GetVehicleMaster(dbHelper.getReadableDatabase(), vhclType);
// set notification builder
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(ctx, "com.myapp.app.fullintent")
.setSmallIcon(R.drawable.ic_yego_logo)
.setContentTitle("New " + (val.contains(",") ? val.split(",")[0] : "") + " Ride Request")
.setContentText(getContent(stopCount, pickLoc, dropLoc))
//.setSound(sound)
.setOngoing(true)
.setTimeoutAfter(10000)
.setDefaults(Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND)
.addAction(R.drawable.payment_success_1, getActionText(R.string.txt_accept, R.color.colorGreen), pendingAcceptIntent)
.addAction(R.drawable.payment_failed_1, getActionText(R.string.txt_reject, R.color.colorRed), pendingRejectIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setFullScreenIntent(contentIntent, true);
Notification incomingCallNotification = notificationBuilder.build();
incomingCallNotification.sound = sound;
//incomingCallNotification.flags = Notification.FLAG_INSISTENT;
final NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifId, incomingCallNotification);
Handler handler = new Handler(Looper.getMainLooper());
long delayInMilliseconds = 10000;
handler.postDelayed(new Runnable() {
public void run() {
try {
Log.e("MyApp", "Handler runs");
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
notificationManager.cancel(notifId);
}catch (Exception e){
}
}
}, delayInMilliseconds);
}
Please suggest how can i set ongoing heads up notification to be on screen regardless of system setting of notification.

New Activity not opening on push notification click

I have a class Home.java which runs first on opening the app when I open it to check if the user is logged in or not.
public class Home extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
The issue I'm facing is when I'm getting a notification for this app, it is starting from LogIn activity instead of going to HomeActivity.
I'm aware that if I want to open a specific activity from a notification, I need to specify getIntent() in the launcher activity, but I don't have any launcher activity.
When I try to implement getIntent() in Home.java class the method is not getting imported since it doesn't extends the Activity class.
Any help!
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}
}
When you want open an activity when click to Notification then use a code like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "Restaurants")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_launcher_background)
.setSound(uri); //applying default notification sound to the notification
//Create an intent to gom HomeActivity
Intent intent = new Intent(this, HomeActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("Restaurants", "demo", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, notificationBuilder.build());
}

Notification Sound Not Playing In Android

Creating Notification Channel
before i create channel i am deleting old channel with channel id.
public class App extends Application {
public static String CHANNEL_ID = "CH1";
public static String CHANNEL_NAME = "CH1 Channel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
public void createNotificationChannel()
{
PrefManager prefManager = PrefManager.getPrefManager(this);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
Uri defaultUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
AudioAttributes attr = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
if (prefManager.getNotificationSound().equals("Bell")) {
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + getPackageName() + "/" + R.raw.bells);
channel.setSound(alarmSound, attr);
} else {
channel.setSound(defaultUri, attr);
}
channel.enableLights(true);
channel.enableVibration(true);
assert notificationManager != null;
//Deleting Notification Channel
try
{
notificationManager.deleteNotificationChannel(channel.getId());
} catch (Exception E) {}
notificationManager.createNotificationChannel(channel);
}
}
}
Posting Notification by using below.
Uri defaultUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + context.getPackageName() + "/" + R.raw.bells);
Notification notification = new NotificationCompat.Builder(context, App.CHANNEL_ID)
.setContentTitle(description)
.setContentText(notificationMessageArray[randomIndex])
.setSmallIcon(R.drawable.ic_buddha)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound((PrefManager.getPrefManager(context).getNotificationSound().equals("Bell") ? alarmSound : defaultUri), AudioManager.STREAM_NOTIFICATION)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.build();
Log.e(TAG, "Posting Notification " + description);
notificationManager.notify(new Random().nextInt() * 100, notification);
before i create channel i am deleting old channel with channel id.
I dont know where i am going wrong in this code.
if i remove code of setting sound from channel and notification default sound not playing but other notification has sound!. i tried with changing importent HIGH to DEFAULT but still same result.
setSound is only set the ringtone. Just add setOnlyAlertOnce(true), so your code will look like this :
Notification notification = new NotificationCompat.Builder(context, App.CHANNEL_ID)
.setContentTitle(description)
.setContentText(notificationMessageArray[randomIndex])
.setSmallIcon(R.drawable.ic_buddha)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound((PrefManager.getPrefManager(context).getNotificationSound().equals("Bell") ? alarmSound : defaultUri), AudioManager.STREAM_NOTIFICATION)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setOnlyAlertOnce(true)
.build();
Check the documentation for the detail

Push notification foreground and background

I've created a simple notification and styled it with different colors and general style using a completely new layer created and designed..
Once I trigger the notification though Firebase Messages, when the app is at the foreground, it works perfectly showing the exact styling I need.
But when the app is in the background, it uses it's fugly default style.
Anyway to fix that? Thanks.
The notification java class file code -
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMessagingServic";
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
Log.d(TAG, "onMessageReceived: Message Received! \n " +
"Title : " + title + "\n" +
"Message : " + message);
sendNotification(title, message);
}
#Override
public void onDeletedMessages() {
}
private void sendNotification(String title, String messageBody) {
final RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_layout);
remoteViews.setTextViewText(R.id.remoteview_notification_short_message, messageBody);
remoteViews.setTextViewText(R.id.notificationDate, title);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = "0";
Uri defaultSoundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notice");
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.minilogored)
.setContentIntent(pendingIntent)
.setContent(remoteViews)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setLights(0xf14d39, 1500, 2000)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Please refer the link to know more about Data message and Display message how to handle in onMessageReceived() callback function.
How to handle notification when app in background in Firebase
https://firebase.google.com/docs/cloud-messaging/android/receive

Wrong activity when click a notification (PendingIntent)

I implemented a notification service in my android app (FirebaseMessagingService). When I click a notification, and the app is closed, the wrong activity is opened. If the notification arrives while the app is open (foreground, background), the activity that is opened is correct.
In the following code, the splash activity (first activity of the project) is opened instead of IntroNoti.class.
This is the code of my FireBaseMessagingService class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
//Log.d(TAG, "From: " + remoteMessage.getFrom());
//Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
Globals.messageIn = true;
sendNotification(remoteMessage);
}
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, Login.class);
Intent intent = new Intent(this, IntroNoti.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_launcher: R.mipmap.ic_launcher;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setContentText("CIAO CIAO")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Thanks to the advice of #Eugen Pechanec I added this instruction in my MainActivity. The "messageid" property is only valued when the app is opened by the notification.
Thank you all!
if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().size() > 0) {
Log.d(TAG, "Received extras in onCreate()");
Bundle extras = getIntent().getExtras();
if (!extras.getString("messageid","").isEmpty()) {
Globals.fromNotification = true;
}
}
Use PendingIntent.FLAG_UPDATE_CURRENT flag with pending intent . It's work for me.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplication(), CHANNEL_ID)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setContentIntent(getPendingIntent())
.setAutoCancel(true);
private PendingIntent getPendingIntent() {
Intent intent = new Intent(getApplication(), ConversationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return PendingIntent.getActivity(getApplication(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

Categories

Resources