unable passing multiple actions to notification action intent - android

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

Related

Android 8.1.0 MainActivity call without click on notification

I have shown push notification using firebase but I faced one issue - when app is open and any notification received then Main Activity oncreate() method automatically call without click on notification, so please anyone can help me for resolved this.
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_IMMUTABLE);
} else {
pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE);
}
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(jsonObject.getString("title"))
.setContentText(jsonObject.getString("body"))
.setAutoCancel(true)
.setNumber(jsonObject.getInt("badge"))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.ic_stat_notification);
notificationBuilder.setColor(getResources().getColor(R.color.sky_blue));
notificationBuilder.setFullScreenIntent(pendingIntent, true);
} else {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", "Messages"));
NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
mChannel.setDescription("description");
mChannel.setShowBadge(true);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(mChannel);
}
int num = (int) System.currentTimeMillis();
notificationManager.notify(num, notificationBuilder.build());
you can do the same using
BroadcastReceiver (android.content.BroadcastReceiver)
And background services (android.app.Service)

samsung wear watch notification issue

Im trying to show notification on wear watch anything is goes correct but My Remote input choice are not visible on samsung watch it will show only title and Body my input choice are not visible on it.
It appears on my phone, but it doesn't appear on my watch connected to my phone. Is there something missing from the code that's required for Android Wear?
I'm using this code for display notification on watch
public void getNotifcation(){
RemoteInput ri = new RemoteInput.Builder(KEY_TEXT_REPLY) .setLabel(body) .setChoices(replyChoices) .build();
NotificationCompat.Action a =
new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red,
null, getReplyPendingIntent())
.addRemoteInput(ri)
.build();
Uri defaultSoundUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_noti_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification))
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{200, 400, 600, 800})
.setOngoing(false)
.setGroup("GROUP")
.setGroupSummary(false)
.setContentIntent(notifyPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(a)
.extend(new NotificationCompat.WearableExtender().addAction(a));
NotificationCompat.WearableExtender extender =
new NotificationCompat.WearableExtender();
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red, "send" ,
getReplyPendingIntent())
.addRemoteInput(ri).build());
notificationBuilder.extend(extender);
//Wear OS requires a hint to display the reply action inline.
NotificationCompat.Action.WearableExtender actionExtender =
new NotificationCompat.Action.WearableExtender()
.setHintLaunchesActivity(true)
.setHintDisplayActionInline(true);
notificationBuilder.addAction(noti.extend(actionExtender).build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(messageBody);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{200, 400, 600, 800});
notificationChannel.setLightColor(Color.RED);
if (defaultSoundUri != null) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(defaultSoundUri, audioAttributes);
}
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId notificationBuilder.build());
}
and here is my pending intent to get choice on wear
public void getReplyPendingIntent(){
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // start a // (i) broadcast receiver which runs on the UI thread or // (ii) service for a background task to b executed,will be doing a broadcast receiver
intent = new Intent(context, FcmBroadcastReceiver.class);
intent.setAction(REPLY_ACTION);
intent.putExtra(KEY_NOTIFICATION_ID, notificationId);
intent.putExtra(KEY_TEXT_REPLY, KeyReply);
return PendingIntent.getBroadcast(getApplicationContext(), 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
} else {
// start your activity
intent = Act_Home.getReplyMessageIntent(this, notificationId, 123);
return PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
}
}

How can I clear previous activity which is open from the tap on notification in Android?

There is a Reminder application. Now users created 5 Reminders. R1, R2, R3, R4, R5.
And for all reminders time is same. So all reminders came in same time. Now I tap on notification which is R1. and when I tap, it opens a particular activity and show according to details because I sent Id of that reminder in intent.
Now I click on R2/R3/R4/R5, it is opening details according to R1 only instead of R2/R3/R4/R5.
Note: In onReceive, I create notification from that. Also, for all reminders, I open same activity, but details on that activity should be different according to Reminder ID. Also, when I send ReminderId/mReceivedId in intent, it is correct, not the same.
Code:
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
Complete code (I call createNotification() from onReceive):
private void createNotification() {
int rowId = getRowId(mReceivedId);
Uri mUri;
if (preferenceManager.getRingtoneUri() != null) {
mUri = Uri.parse(preferenceManager.getRingtoneUri());
} else {
mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
String mTitle = reminder.getTitle();
String id = "1";
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Intent editIntent;
if (SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
assert mNotificationManager != null;
NotificationChannel mChannel = mNotificationManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, mTitle, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
builder.setContentTitle(mTitle)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle(mTitle)
.setSmallIcon(R.drawable.ic_alarm_black_24dp)
.setSound(mUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Have you completed your task?"))
.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
.addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent);
builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
} else {
builder = new NotificationCompat.Builder(context, id);
editIntent = new Intent(context, ReminderDetailActivity.class);
editIntent.putExtra(REMINDER_ID, mReceivedId);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
editIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
editIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, rowId, editIntent, 0);
builder.setContentTitle(mTitle)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle(mTitle)
.setSmallIcon(R.drawable.ic_alarm_black_24dp)
.setSound(mUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_icon_alarm, context.getString(R.string.pay_now), pendingIntent)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Have you completed your task?"))
.setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)
.setPriority(Notification.PRIORITY_HIGH);
builder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
}
Notification notification = builder.build();
mNotificationManager.notify(rowId, notification);
}
Welcome to code party 🎉
As i seen, u want start an activity when another is already opened and it can’t get other extras.
So you must before sending another intent, clear bundle or finish activity.
Edited:
use this in your activity
#Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent); //just add this line when overrided
}
do it and update me

Redirect to specific screen as per notification - android

I have receive three different screens in my app:
Reading,
Walking, and
Sleeping
How do I identify the specific notification to redirect to in each screen?
To do so, you must specify a content intent defined with a PendingIntent object and pass it to setContentIntent().
The following snippet shows how to create a basic intent to open an activity when the user taps the notification:
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, Reading.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
This is clearly mentioned in Android developer site
private final String CHANNEL_ID = "channel1";
private final String CHANNEL_NAME = "channel_one";
private NotificationManager notificationManager;
private NotificationManager getNotificationManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
return notificationManager;
} else {
return notificationManager;
}
}
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("type", "type");
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setShowBadge(true);
getNotificationManager().createNotificationChannel(channel);
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
builder.setColorized(true);
builder.setChannelId(CHANNEL_ID);
builder.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
} else {
builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
}
builder.setContentTitle("Title");
builder.setContentText("Message");
Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(notificationSound);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_bottom_logo);
builder.setLargeIcon(/*BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)*/getBitmapFromDrawable(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.ic_launcher)));
builder.setContentIntent(pendingIntent);
getNotificationManager().notify((int) SystemClock.uptimeMillis(), builder.build());

Vibrate and Sound defaults on notification

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)

Categories

Resources