I'm working on android app with system of notifications and i need the android device to push the notification with a specific sound i stored on assets folder
this is my java code for notification :
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("Calcupital")
.setContentTitle("Calcupital")
.setContentText("User Information has been updated successfully")
.setSmallIcon(R.drawable.login)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
Assuming that my sound stored like that : (\assets\hopo.mp3)
how to make this notification pushed with this sound without changing the push notification systems for other apps by changing the sound from the list that android device offered !!.
I hope my question is very clear to you :)
To combine the answers here and using the two answers from these questions:
How to add sound to notification?
How to get URI from an asset File?
Try this:
Uri sound = Uri.parse("file:///android_asset/hopo.mp3");
Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("Calcupital")
.setContentTitle("Calcupital")
.setContentText("User Information has been updated successfully")
.setSmallIcon(R.drawable.login)
.setSound(sound);
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
You need to place your sound file to res/raw directory.
Then add this code into current code
final String packageName = context.getPackageName();
notification.sound =
Uri.parse("android.resource://" + packageName + "R.raw.hopo");
see this link for more details
http://developer.android.com/reference/android/app/Notification.Builder.html#setSound(android.net.Uri)
you can set default sound using
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alarmSound != null) {
mBuilder.setSound(alarmSound);
}
if you want custom sound just use different Uri. how to get Uri from assets? check this topic
To get the resource:
Uri alarmSound = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.somefile);
** the raw folder must be created inside res folder and add youre sound file **
To set up:
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setContentText(message)
.setSound(alarmSound) // -> add this one
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
Related
I have Firebase messaging with my andriod application. I am using Firebase to send push notifications. I want to change the default notification sound to a custom one. how can i do it ?
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.ic_notif)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setCustomBigContentView(remoteViews)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))
;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(id) /* ID of notification */, notificationBuilder.build());
}
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.pop);
notification.defaults |= Notification.DEFAULT_VIBRATE;
Use above code to add custom sound from resources.
The above code can be used if we are using Notification class.
Notification notification = new Notification(icon, tickerText, when);
As you are using NotificationBuilder, use the below code.
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.ic_notif)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pendingIntent)
.setCustomBigContentView(remoteViews)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))
;
Use setSound() method to set the sound
if(!silent) { // check if phone is not in silent mode
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(9999, notificationBuilder.build());
}
}
Or you can use
{
"to" : "XXYYXXYY...",
"notification" : {
"body" : "The stock opened on a bullish note at Rs. 449 and touched a high of Rs. 461.35, up 5.06 per cent over its previous closing price on the BSE. A similar movement was seen on the NSE where the stock opened at Rs. 450 and hit a high of Rs. 463.70, up 5.32 per cent.",
"title" : "Stocks in focus: Kalpataru Power, Punj Lloyd, J B Chem, Bharti Airtel",
"icon" : "ic_stock",
"sound" : "res_notif_sound"
}
}
If you want to use default sound of the device, you should use:
"sound": "default".
I'm not getting sound, vibration or light when receiving a notification. Can someone please tell me what I'm missing?
Also I have some other questions:
1.) I only get the specified icon when the app is open. When the app is closed I get the android logo icon (I guess thats because I havent defined an app icon yet).
2.) The ticker text is only shown when the app is open.
3.) When the app is open I dont get the content text, only the content title.
SOLUTION: This happens because I am using com.google.android.gms:play-services-gcm:8.4.0 over the previous version.
Make sure that on the server you send a notification array containing only the key/value pair e=0 while sending your message information in the data array.
This problem has already a great answer here: After updating Google play services to 8.4.0 push notifications displayed by themselves
This is my Source:
public class MyGcmListenerService extends GcmListenerService {
private final static String TAG = "GCM_Listener";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from + " (" + message);
// Sets an ID for the notification
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.sharedPreferenceStore_default), Context.MODE_PRIVATE);
int mNotificationId = sharedPreferences.getInt("id_notification", 0);
mNotificationId++;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.all_picks_made_indicator)
.setAutoCancel(true)
.setContentTitle("Product - " + mNotificationId)
.setContentText(message)
.setTicker("Product Notification received");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, DetectLoginActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
Notification notification = mBuilder.build();
notification.defaults = Notification.DEFAULT_ALL;
mNotifyMgr.notify(mNotificationId, notification);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("id_notification", mNotificationId);
editor.commit();
}
}
Custom Sound for Push Notification
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pop);
In your code change
Notification notification = mBuilder.build();
notification.defaults = Notification.DEFAULT_ALL;
mNotifyMgr.notify(mNotificationId, notification);
To.
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.pop);
notification.defaults |= Notification.DEFAULT_VIBRATE;
mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
mBuilder.setLights(getResources().getColor(R.color.mainColor), 1000, 1000);
you can set color and vibrate on the builder object
You're missing something like this:
long[] pattern = new long[]{0, 100, 200, 100}; //two short beeps
mBuilder.setVibrate(pattern);
Notification note = mBuilder.build();
note.vibrate = pattern;
That will give you vibrations. Look into lights, I don't have that code at hand atm.
In the following code I create a notification and display it with vibration and sound. As it is now it works perfectly fine.
However, if I change to using sounds from the RingtoneManager, as I have seen multiple other examples do, no sound gets played (no error messages, just no sound). Does anyone know how I can get those sounds to play?
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.icon);
builder.setContentTitle("Title");
builder.setContentText("Text");
builder.setStyle(new NotificationCompat.InboxStyle());
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
Uri alarmsound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification); // Works fine
// Uri alarmsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // Doesn't work
builder.setSound(alarmsound);
long[] pattern = {1000, 500, 500, 1000};
builder.setVibrate(pattern);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
notificationManager.notify(1, notification);
I'm using MixPanel to send push notification and on the custom payload I add the following code:
{"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
Maybe this helps found here code will look like this.
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
In order to send notification + sound using mixpanel, you need to do the following:
add the following code to the onCreate:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
Send notification from mixpanel and see it received. This will send notification on create with default sound configured on the user's device.
try following code
Notification notification = new Notification(R.drawable.appicon,
"Notification", System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_SOUND;
final Notification notification =
new Notification(iconResId, tickerText, System.currentTimeMillis());
final String packageName = context.getPackageName();
notification.sound =
Uri.parse("android.resource://" + packageName + "/" + soundResId);
Assuming you have a declaration...
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setTicker(title)
.setWhen(ts)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message);
... variable constructed somewhere in your code, try this:
final String ringTone = "default ringtone"; // or store in preferences, and fallback to this
mBuilder.setSound(Uri.parse(ringTone));
The default GCMReceiver in the Mixpanel library for Android that handles incoming push notifications from Mixpanel doesn't include sounds. You'll need to write your own BroadcastReceiver to process incoming messages from Mixpanel.
You can take a look at Mixpanel's documentation for using the low level API at : https://mixpanel.com/help/reference/android-push-notifications#advanced - then you an apply the advice from the other answers to do anything you'd like with your custom data payload.
There are at least 7 questions on Stackoverflow related to this, I have tried every single suggestion and solution multiple times and none of them have worked. Here is my latest attempt:
private Notification createNotification() {
Notification notification = new Notification();
if(notifyImage=="food")
{
notification.icon = R.drawable.food;
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://com.example.memoryGuide/raw/start");
}
else
{
notification.icon = R.drawable.bar;
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://com.example.memoryGuide/raw/start");
}
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
You can see the two times I try and use a sound which never works, but the icons work perfectly. I do not know if I am missing anything in order to get this to work, but all of the code I am using is in my post.
My sound file is in res/raw/start.mp3, I can get this sound to work when pressing a button, so the sound is fine.
I think the package name is right, my application at has this at the top of each class:
package com.example.memoryGuide;
Any ideas why the sound never plays?
use
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + getPackageName() + "/raw/start");
Note one thing.
String android.content.ContextWrapper.getPackageName()
returns the package name of your android aplication. And
package com.example.memoryGuide;
shows the package name of your source package name.
If this one work for you. Please vote up..........
Just put your sound file in Res\raw\siren.mp3 folder ::
Then put this code..This will definitely work for you.
For Custom Sound ::
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.siren);
For Default Sound ::
notification.defaults |= Notification.DEFAULT_SOUND;
For Custom Vibrate ::
long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;
For Default Vibrate ::
notification.defaults |= Notification.DEFAULT_VIBRATE;
I was having a similar problem while testing on API 23. While I do not know the cause of the problem, I did manage to find a workaround that got the job done.
In one of Google's examples, a notification is constructed thusly:
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.ic_launcher)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText(getString(R.string.geofence_transition_notification_text))
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
Notice the class NotificationCompat.Builder. For some reason which is beyond me, this did not play any sound other than the default one. In other words, only this worked:
// Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // Default
...
builder.setSound(soundUri); //Set the sound to play
But this didn't:
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
getPackageName() + "/" + R.raw.name_of_sound);
After simply replacing the builder class with Notification.Builder (available for API >= 11) the "this didn't" section above started working as expected.
Conclusion: use this if you're willing to sacrifice (or are not interested in) compatibility with API < 11.