Notification sound from URI parse does not work - android

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.

Related

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

Android push notification how to play default sound

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.

Android - Push Notification sound and open activities issues

This is a two part issue. I have push notifications work with my app but I can't get a custom sound to work, 1. 2. I can't get the notifications to open the app when you click on it from the notification bar.
This is the code below. I've tried various things to import a custom sound. The sound in in my assets/sounds folder. Will that be carried over with the apk when installed and how to I access it? I'm using webview as well like to open the app to a specific link from the notification, can that be done also?
private void sendGCMIntent(final Context theContext, String theMessage)
{
int icon = R.drawable.noti_icon;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
theContext.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, theMessage, when);
String title = theContext.getString(R.string.app_name);
Intent notificationIntent = new Intent();
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(theContext, 0, notificationIntent, 0);
notification.setLatestEventInfo(theContext, title, theMessage, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//String path = "file:///android_asset/sounds/soft.mp3";
//File file = new File(path);
//Log.i(TAG,"Sound exists : " + file.exists());
Uri soundUri = Uri.parse("file:///android_asset/sounds/soft.mp3");
if (soundUri != null) {
notification.sound = soundUri;
}
else {
notification.defaults |= Notification.DEFAULT_SOUND;
}
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}

Push Notification not receiving Using GCM in Galaxy Nexus with Android 4.2.1

Right now I am using 3 devices for testing: Samsung S7500, Galaxy Mexus, HTC explore. If the devices are active, then I am receiving push notification in all three devices. If it is in idle state(locked/sleep), then also I am receiving push notification in all three devices. But if it is offline when the push message has been send, the time I am getting online should receive all pending notifications as per the documentation. But in this case I am not receiving notification in all the devices. Specially in Galaxy Nexus, sometime I am receiving if it is in idle state and sometime not. Where I am getting wrong? Can anyone help me?
String posted to GCM server from Third party server(.Net) end: where "i" is the current time.
String postdata= "collapse_key=score_update"+i+"&time_to_live=2419200&delay_while_idle=1&data.message=‌​"+ message + "&data.time=" + System.DateTime.Now.ToString()
+ "&registration_id=" + deviceToken + "";
Mentioned all required permissions in manifest as per documentation including Wakelock. This is my code for notiication in GCMIntentService class:
int icon = R.drawable.notif;
long when = System.currentTimeMillis();
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
Intent notificationIntent = new Intent(context, DemoActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, (int) when,
notificationIntent,0);
RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.notify);
contentView.setImageViewResource(R.id.ImageViewpnotify, icon);
contentView.setTextViewText(R.id.TextViewpnotify, message);
notification.contentView = contentView;
notification.contentIntent= intent;
notification.icon = icon;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.ledARGB = 0xffff0000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.ledOnMS = 100;
notification.ledOffMS = 100;
notificationManager.notify((int)when, notification);
i know it is late to answer your question, but i had the same problem and i managed to solve it using the following link:
https://gist.github.com/mgartner/7092333
it is a bug in some devices where the service goes into idle state and stops receiving any notifications, the solution is by forcing it to restart every 5 min.
also you can use the following link to help u in customizing your gcmreceiver:
http://code.google.com/p/gcm/source/browse/gcm-client/src/com/google/android/gcm/GCMBaseIntentService.java?r=8094cc6410b7dc2db452eb19cc9274fda1b2d6a2

Categories

Resources