Android push notification how to play default sound - android

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.

Related

Notification image never displays in Android

If suppose I create Notification icons by uploading a png image using Image Asset tool from Android Studio by choosing type as notification would it generate all required icons with the dimensions as needed by notification icon spec? if Yes, then there should not be any problem displaying this icon in the notification bar, isn't it? hmm it doesn't in my case but rather it shows the default App icon no matter what. Below is my code. Any guess why its failing, perhaps this is just a cosmetic issue through.
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("VEDRISE",
"Vedic Notifications",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Will display daily Panchang notificatons");
mNotificationManager.createNotificationChannel(channel);
}
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// URL url = new //URL("https://66.media.tumblr.com/ec76b7d7e0529af6e3a437edb6c6c255/tumblr_phiur//jqePq1xp0noco1_75sq.png");
// Bitmap image = //BitmapFactory.decodeStream(url.openConnection().getInputStream());
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "VEDRISE")
.setSmallIcon(R.drawable.sunrise) // notification icon
// .setLargeIcon(image)
.setContentTitle(title) // title for notification
.setContentText(content)// message for notification
.setSound(alarmSound) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
Intent intent = new Intent(context, this.getClass());
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
int id = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Log.d("VedicHoroo", String.format("id: %d", id));
mNotificationManager.notify( id, mBuilder.build());
Just to give you some scope, this requirement is for local notification which will trigger by the AlarmReceiver. The receiver is triggered by Alarm without issues but the Notification does not display image which is set by setSmallIcon instead it display only the App Icon
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.build();
Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_notification" />
add this line in the manifest.xml file in application block

How to set default device Alarm tone for scheduled notification?

I want to set default device alarm tone for my scheduled notification as normal notification sounds are hard to notice.
I try to get alarm tone by: Uri alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
and then simply set it with: builder.setSound(alarmTone);
All I get is vibration with out any alarm tone sound. Any ideas?
Whole code:
private Notification getNotification(String content) {
Uri alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this,
Receiver.NOTIFICATION_CHANNEL_ID
);
builder.setContentTitle("Title");
builder.setSmallIcon(R.drawable.x);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
builder.setSound(alarmTone);
builder.setContentText(content);
builder.setAutoCancel(true);
return builder.build();
}
Try Below Code:
1.builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
2.mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Put your preferred alarm in "Res\raw\{your_ringtone}.mp3"
and then do like this:
Notification mNotification = builder.build();
mNotification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.{your_ringtone});

Android: Push Notification has no Sound/Vibration/Light

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.

How to make push notification with specific sound?

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

Notification sound from URI parse does not work

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.

Categories

Resources