Im using a Broadcast Receiver to send notification at custom time. I use a MediaPlayer to play a sound everytime it fires. The problem is it sometimes just suddenly stops in the middle of the sound playing. This is my code:
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
#SuppressLint("InvalidWakeLockTag")
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TRAININGCOUNTDOWN");
wl.acquire(10*60*1000L /*10 minutes*/);
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon);
Intent inteent = new Intent(context, MainActivity.class);
inteent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, xx, inteent, PendingIntent.FLAG_UPDATE_CURRENT);
xx = xx + 1;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentTitle("بانگ")
.setContentText(notTitle)
.setPriority(NotificationCompat.PRIORITY_HIGH)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationId is a unique int for each notification that you must define
// Put here YOUR code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.c4kurd.bang");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.c4kurd.bang",
"بانگ",
NotificationManager.IMPORTANCE_HIGH
);
channel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
assert notificationManager != null;
int id = context.getResources().getIdentifier(cc(prefs.getString("voices","")), "raw", context.getPackageName());
// Toast.makeText(context, prefs.getString("voices",""),Toast.LENGTH_SHORT).show();
MediaPlayer mp= MediaPlayer.create(context, id);
notificationManager.notify(xx, builder.setVibrate(new long[]{1000,1000}).build());
mp.start();
wl.release();
}
I don't know the issue. Is it because mp.start() is before the Wake Lock?
Thanks in advance.
DEFAULT: This line returns the default notification sound
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
CUSTOM: This line chooses a custom notification sound:
(put this in RAW (resources) folder)
Uri notificationSound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.my_custom_sound_file);
Choose one of the above and add it to your notification:
setSound(notificationSound)
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentTitle("Your Title")
.setContentText("Your Content")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setSound(notificationSound)
.setAutoCancel(true);
Remove all extra lines you used your own MediaPlayer.
Related
Be informed, we are trying to send notification with a button using Addaction. The button Start has a intent that directly opens a url in a webview, which works perfectly fine with code given below
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//int notification_id = nid!=null ? Integer.parseInt(nid) : MainActivity.ASWV_FCM_ID;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
int notification_id=m;
Intent buttonIntent = new Intent(this, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",notification_id);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent,0);
String channelId = MainActivity.asw_fcm_channel;
Uri soundUri=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/pristine");
NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, tag, pendingIntent).build();
NotificationCompat.Action action1 = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Dismiss", btPendingIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder1 = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(false)
.addAction(action)
.addAction(action1)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
// Configure the notification channel.
mChannel.setDescription("Common notifications");
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setSound(soundUri, attributes);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(mChannel);
}
Notification noti = notificationBuilder1.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notification_id, notificationBuilder1.build());
Update:
I'm sorry but i'm not actually a expert or a regular coder in android java, so you gotta help me here a little bit more. I have passed on my notification id down in the code, but the problem here is how do i invoke removeNotification in the pendingIntent which also carries my url to where the link will go onclick
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("uri", uri);
intent.putExtra("notificationId",notification_id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
public static void removeNotification(int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
}
}
But we also like the notification to be dismissed simultaneously onclick. We tried using .setAutocancel (true) and notification flags like FlAG_AUTO_CANCEL, but the button just does first action right of going into webview url and not cancelling the notification.
Shall appreciate should you help us out.
Send the notification id in the intent to activity and use the code to cancel.
public static void removeNotification(Context context, int notification_id) {
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notification_id);
}
} catch (Exception e) {
Timber.d(e);
}
}
Intent intent = getIntent();
if (intent.hasExtra("notificationID")) {
removeNotification(context, intent.getIntExtra("notificationID", 0));
}
Please be informed we are able to send push notifications with addAction (buttons). But we are unable to simply direct it to app's webview url onclick of those buttons despite providing intents.
Further explaining, we have two buttons(addAction): Receive, Dismiss in the heads up push notification. We would like Receive button to direct to app's webview url onclick and Dismiss button to close the notification.
The Code is as given below
private void sendMyNotification(String title, String message, String click_action, String uri, String tag, String nid) {
//On click of notification it redirect to this Activity
Intent intent = new Intent(click_action);
intent.putExtra("uri", uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
int notification_id = nid!=null ? Integer.parseInt(nid) : MainActivity.ASWV_FCM_ID;
String channelId = MainActivity.asw_fcm_channel;
Uri soundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/pristine.mp3");
Uri uri = Uri.parse("https://www.google.com/");
Intent ur = new Intent(Intent.ACTION_VIEW, uri);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel (true)
.setSound(soundUri)
.addAction(R.mipmap.ic_launcher,"Receive",ur)
.addAction(R.mipmap.ic_launcher,"Dismiss",ur)
.setSound(soundUri)
.setContentIntent(pendingIntent);
Notification noti = notificationBuilder.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
// Configure the notification channel.
mChannel.setDescription("Common notifications");
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.setSound(soundUri, attributes);
mChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
mChannel.enableVibration(true);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(notification_id, notificationBuilder.build());
}
}
Please guide us as where we are going wrong.
I am working on Android App with Firebase notification service FCM. and I recives notification successfully. but after I recive it is not showin in Android 10 (it work in 9 and 8 and smaller versions).
This is my showing notification code, I dont know what I missed. I check about if there is any changed with 10 but I dont see that...
My method:
private void sendNotification(String messageBody, String title) {
Intent intent;
if(type.equals("order_pending") || type.equals("order_declined")){
intent = new Intent(this, myOrdersActivity.class);
}else { 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 = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int f =0;
// 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_HIGH);
notificationManager.createNotificationChannel(channel);
}
// EventBus.getDefault().post(eventObject);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isActive", true)) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Intent dialogIntent = new Intent(this, MainActivity.class)
.putExtra("ac", "1");
// sendBroadcast(dialogIntent);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
f =1;
// startActivity(dialogIntent);
}
if(f==0) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Any help please?
and Thanks
The ship has sailed, but:
worked skeleton (Java):
void sendNotif(int icon, String sText) {
String channel_id = "1002";
String sTitle = getString(R.string.app_name);
Intent notificationIntent = new Intent(this, activityMain.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android 8.0 (API level 26) and higher
// https://developer.android.com/training/notify-user/build-notification
CharSequence name = "statusbar";
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channel_id, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel_id)
.setSmallIcon(icon)
/*.setContentTitle(sTitle)*/
.setContentText(sText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(contentIntent)
.setAutoCancel(false);
// notificationId is a unique int for each notification that you must define
// and remember for delete notification
notificationManager.notify(0, builder.build());
}
else {
// Android 7.1 (API level 25) and lower
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(getApplicationContext())
.setTicker(sTitle)
.setContentTitle(sTitle)
.setContentText(sText)
.setSmallIcon(icon)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
// for BIG icon:
//notification.contentView.setImageViewResource(android.R.id.icon, R.drawable.icon);
mNotificationManager.notify(0, notification);
}
}
I am adding custom sound for my application. The custom ringtone is playing when the application is in the foreground but the custom sound is not playing when the application is in background.
private void sendMyNotification(String message) {
Intent intent = new Intent(this, BaseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ring);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.mipmap.iconfinal)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(soundUri != null){
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri,audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(1, notificationBuilder.build());
}
First you need to pass your sound file name from server side.
like below example:
{
"to": "firebase_notification_token",
"notification": {
"title": "Push notification title",
"body": "Push body",
"sound": "filename", <-- point to src/res/raw/filename.mp3
}
}
You need to add below code to play custom sound while app is in background.
val channelId = getString(R.string.app_name)
val NOTIFICATION_SOUND_URI =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.filename)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
val notification: Notification
notification = notificationBuilder.setSmallIcon(R.drawable.ic_logo_white).setTicker(getString(R.string.app_name)).setWhen(0)
.setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setSound(NOTIFICATION_SOUND_URI)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(messageBody)
.build()
For more detail refer to this Document.
Thanks to Ilya Eremin for great article.
I'm trying to get a default vibrate and sound alert when my notification comes in, but so far no luck. I imagine it's something to do with the way I set the defaults, but I'm unsure of how to fix it. Any thoughts?
public void connectedNotify() {
Integer mId = 0;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle("Device Connected")
.setContentText("Click to monitor");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(getApplicationContext(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setOngoing(true);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_SOUND;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, note);
}
Some dummy code might help you.
private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
.setWhen(System.currentTimeMillis()).......;
//Vibration
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
//LED
builder.setLights(Color.RED, 3000, 3000);
//Ton
builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));
return builder;
}
Add below permission for Vibration in AndroidManifest.xml file
<uses-permission android:name="android.permission.VIBRATE" />
An extension to TeeTracker's answer,
to get the default notification sound you can do as follows
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle("Device Connected")
.setContentText("Click to monitor");
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
This will give you the default notification sound.
Notification
Vibrate
mBuilder.setVibrate(new long[] { 1000, 1000});
Sound
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
for more sound option
Its work fine to me,You can try it.
protected void displayNotification() {
Log.i("Start", "notification");
// Invoking the default notification service //
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setAutoCancel(true);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
mBuilder.setTicker("New message from PayMe..");
mBuilder.setSmallIcon(R.drawable.icon2);
// Increase notification number every time a new notification arrives //
mBuilder.setNumber(unMber_unRead_sms);
// Creates an explicit intent for an Activity in your app //
Intent resultIntent = new Intent(this, FreesmsLog.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(FreesmsLog.class);
// Adds the Intent that starts the Activity to the top of the stack //
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// mBuilder.setOngoing(true);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_SOUND;
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on. //
mNotificationManager.notify(notificationID, mBuilder.build());
}
This is a simple way to call notification by using default vibrate and sound from system.
private void sendNotification(String message, String tick, String title, boolean sound, boolean vibrate, int iconID) {
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);
Notification notification = new Notification();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (sound) {
notification.defaults |= Notification.DEFAULT_SOUND;
}
if (vibrate) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
notificationBuilder.setDefaults(notification.defaults);
notificationBuilder.setSmallIcon(iconID)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setTicker(tick)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Add vibrate permission if you are going to use it:
<uses-permission android:name="android.permission.VIBRATE"/>
Good luck,'.
I m using the followung code and its working fine for me .
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
To support SDK version >= 26, you also should build NotificationChanel and set a vibration pattern and sound there. There is a Kotlin code sample:
val vibrationPattern = longArrayOf(500)
val soundUri = "<your sound uri>"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val attr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel =
NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.setSound(soundUri, attr)
notificationChannel.vibrationPattern = vibrationPattern
notificationManager.createNotificationChannel(notificationChannel)
}
And this is the builder:
with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
setContentTitle("Some title")
setContentText("Some content")
setSmallIcon(R.drawable.ic_logo)
setAutoCancel(true)
setVibrate(vibrationPattern)
setSound(soundUri)
setDefaults(Notification.DEFAULT_VIBRATE)
setContentIntent(
// this is an extension function of context you should build
// your own pending intent and place it here
createNotificationPendingIntent(
Intent(applicationContext, target).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
)
)
return build()
}
Be sure your AudioAttributes are chosen right to read more here.
// set notification audio
builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR
builder.setDefaults(Notification.DEFAULT_SOUND);
For Kotlin you can Try this.
var builder = NotificationCompat.Builder(this,CHANNEL_ID)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)