Notification Sound Not Playing In Android - java

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

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.

Custom sound on notification

I am trying to add custom sound in notification pushed by my app. I tried following code so far
Channel code
private void createFullIntentChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/mysound.mp3" ) ;
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
String NOTIFICATION_CHANNEL_ID = "com.yego.myapp.fullintent";
String channelName = "Full Intent Channel";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setSound(sound, attributes);
manager.createNotificationChannel(chan);
}
}
Notification
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/mysound.mp3" ) ;
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(ctx, "com.yego.myapp.fullintent")
.setSmallIcon(R.drawable.ic_yego_logo)
.setContentTitle("New Booking")
.setContentText("From " + pickLoc + "\n" + "To " + dropLoc)
.setSound(sound)
.setOngoing(true)
.setTimeoutAfter(15000)
.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_HIGH)
.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);
It plays default notification sound. What i am missing ?
Also it plays default sound only once. I need it to play untill user clicked on notification or action buttons..
Please suggest

o android notification sound is not playing

This is my code for making notification and notification is showing but not playing sound please help me to identify mistakes in my code and do we need any permission to play sound,vibrate for notification?
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "my_channel_01";
CharSequence name = "oreiomilla";
String description ="i love me";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel .setSound(alarmSound,attributes);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages. "+ct)
.setSmallIcon(R.drawable.ic_app_icon)
.setChannelId(CHANNEL_ID) .setTicker("Showing button notification") //
.addAction(android.R.drawable.ic_dialog_alert, "Visit", pIntent) // accept notification button
.addAction(android.R.drawable.ic_dialog_email, "ignore", pIntent)
.build();
mNotificationManager.notify(notifyID, notification);
To set a sound to notifications in Oreo, you must set sound on NotificationChannel and not on Notification Builder itself. You can do this as follows
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
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);
}
Try this it will work for you.
private void BigTextNotificationForDays(Context context, String Message, String Author) {
Intent resultIntent = new Intent(context, SplashActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) Calendar.getInstance().getTimeInMillis(), resultIntent, PendingIntent.FLAG_ONE_SHOT);
//To set large icon in notification
// Bitmap icon1 = BitmapFactory.decodeResource(getResources(), R.drawable.big_image);
//Assign inbox style notification
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(Message);
bigText.setBigContentTitle(context.getString(R.string.app_name));
bigText.setSummaryText(Author);
//build notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context,createNotificationChannel(context))
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(Message)
.setStyle(bigText)
.setLargeIcon(icon)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setVibrate(new long[]{1000, 1000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
//.setOngoing(true);
// Gets an instance of the LocalNotificationManager service
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//to post your notification to the notification bar
mNotificationManager.notify(3730, mBuilder.build()); // (int) System.currentTimeMillis() set instead of id. if at a time more notification require
}
public static String createNotificationChannel(Context context) {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String channelId = "Channel_id";
// The user-visible name of the channel.
CharSequence channelName = "Application_name";
// The user-visible description of the channel.
String channelDescription = "Application_name Alert";
int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
boolean channelEnableVibrate = true;
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableVibration(channelEnableVibrate);
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
return channelId;
} else {
// Returns null for pre-O (26) devices.
return null;
}
}

Custom Sound Not Playing Firebase Messaging Android

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));

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

Categories

Resources