set different colors for notification actions - java

Hi I am setting a notification for incoming call with two actions : Answer and Decline . I need to set Green color for Answer action and red for Decline . But i couldnt find a solution.
Here is my code :
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext,"Call")
.setSmallIcon(R.drawable.ic_stat_rider_logo)
.setContentIntent(contentIntent)
.setContentTitle(generalFunc.retrieveLangLBl("","LBL_SINCH_NOTIFICATION_CONTENT"))
.setContentText(call.getHeaders().get("Name") +" "+ generalFunc.retrieveLangLBl("","LBL_SINCH_NOTIFICATION_TITLE"));
builder.addAction(getServiceNotificationAction(mContext, denyCallIntent(mContext,call),R.drawable.ic_call_icon, R.string.decline));
builder.addAction(getServiceNotificationAction(mContext, answerCallIntent(mContext,call),R.drawable.com_facebook_close, R.string.answer));
if (callActivityRestricted()) {
builder.setFullScreenIntent(contentIntent, true);
builder.setPriority(NotificationCompat.PRIORITY_HIGH);
builder.setCategory(NotificationCompat.CATEGORY_CALL);
}
private NotificationCompat.Action getServiceNotificationAction(Context context, Intent intent, int iconResId, int titleResId) {
PendingIntent pendingIntent = Build.VERSION.SDK_INT >= 26 ? PendingIntent.getForegroundService(context, 0, intent, 0)
: PendingIntent.getService(context, 0, intent, 0);
return new NotificationCompat.Action(iconResId, context.getString(titleResId), pendingIntent);
}
I tried setColor() , but it sets unique color for both actions.
Please help me to solve this . thanks in advance

I have tried your code and achieved it with the help of Spannable class.
public void sendOnChannel1(View v) {
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", message);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setColorized(true)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.mipmap.ic_launcher, getMyActionText(R.string.answer,R.color.green), actionIntent)
.addAction(R.mipmap.ic_launcher, getMyActionText(R.string.decline,R.color.red), actionIntent)
.build();
notificationManager.notify(1, notification);
}
Here is a helping method which i used:
private Spannable getMyActionText(#StringRes int stringRes, #ColorRes int colorRes) {
Spannable spannable = new SpannableString(this.getText(stringRes));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
spannable.setSpan(
new ForegroundColorSpan(this.getColor(colorRes)), 0, spannable.length(), 0);
}
return spannable;
}

Related

Android Notification not displaying action buttons

Below is the method I am using to build a notification for a media player application. Currently, the song information is being displayed correctly but the action buttons for prev, play, next are not being displayed.
This is what is displayed with the notification after calling buildNotification();
private void buildNotification(Notification.Action action) {
String ID = "sage.musicplayer.Service.MusicService";
/*Bitmap albumArtBitmap = null;
if(album_art != null) {
try {
albumArtBitmap = Glide.with(getApplicationContext()).asBitmap().load(album_art).into(100, 100).get();
}catch(Exception e) {
e.printStackTrace();
}
}else if(albumID > -1) {
albumArtBitmap = musicUtils.getAlbumArt(albumID);
}else{
albumArtBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.new_album_art);
}*/
Intent intent = new Intent(MusicService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
Intent intentPrev = new Intent(ACTION_PREV);
Intent intentPlayPause;
if(isPng())
intentPlayPause = new Intent(ACTION_PAUSE);
else
intentPlayPause = new Intent(ACTION_PLAY);
Intent intentNext = new Intent(ACTION_NEXT);
PendingIntent pendingPrev = PendingIntent.getActivity(this, 0, intentPrev, PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingPlayPause = PendingIntent.getActivity(this, 0, intentPlayPause, PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingNext = PendingIntent.getActivity(this, 0, intentNext, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext());
notification.setContentTitle(songTitle)
.setWhen(System.currentTimeMillis())
.setChannelId(ID)
.setSmallIcon(R.drawable.logo)
.setContentText(songArtist)
.setLargeIcon(musicUtils.getAlbumArt(albumID))
.setDeleteIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(MediaSessionCompat.Token.fromToken(mediaSession.getSessionToken())))
.addAction(R.drawable.prev, "Prev", pendingPrev)
.addAction(R.drawable.playbutton, "Play", pendingPlayPause)
.addAction(R.drawable.next, "Next", pendingNext);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
notificationManagerCompat.notify(NOTIFY_ID, notification.build());
}
If your drawables (R.drawable.prev, etc) are vectorial and not images, it won't work. I had the same issue today.

How can I know which button was clicked in the notification?

I am developing an application, I have 2 buttons in an on the notification. How can I know which button the user has clicked?
This my Notification codes;
public void NotificationSettings(Context context){
Intent stateIntent = new Intent(context, MyBroadcastReceiver.class);
stateIntent.putExtra("id", 100);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, stateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder = new NotificationCompat.Builder(context, "access2020")
.setSmallIcon(R.drawable.ic_baseline_add_alert_24)
.setContentTitle("Academy Notification")
.setContentText("Hey this is an important notifications")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.ic_baseline_add_alert_24, "Set Active", pendingIntent)
.addAction(R.drawable.ic_baseline_add_alert_24,"Dismiss", pendingIntent);
notificationManager = NotificationManagerCompat.from(context);
}
and My Broadcast
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();
int notificationId = intent.getIntExtra("id", 0);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.cancel(notificationId);
}
You should pass an identifier to the intent as an extra and then retrieve in your BroadcastReceiver.
public void NotificationSettings(Context context){
// put an extra identifier for Set Active Action
Intent setActiveStateIntent = new Intent(context, MyBroadcastReceiver.class);
setActiveStateIntent.putExtra("id", 100);
setActiveStateIntent.putExtra("action", "Action.SetActive");
PendingIntent setActivePendingIntent =
PendingIntent.getBroadcast(context, 0, setActiveStateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// put an extra identifier for Dismiss
Intent dismissStateIntent = new Intent(context, MyBroadcastReceiver.class);
dismissStateIntent.putExtra("id", 100);
dismissStateIntent.putExtra("action", "Action.Dismiss");
PendingIntent dismissPendingIntent =
PendingIntent.getBroadcast(context, 0, dismissStateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder = new NotificationCompat.Builder(context, "access2020")
.setSmallIcon(R.drawable.ic_baseline_add_alert_24)
.setContentTitle("Academy Notification")
.setContentText("Hey this is an important notifications")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.ic_baseline_add_alert_24, "Set Active", setActivePendingIntent)
.addAction(R.drawable.ic_baseline_add_alert_24,"Dismiss", dismissPendingIntent);
notificationManager = NotificationManagerCompat.from(context);
}
Then in your BroadcastReceiver you can do the following:
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("action").equals("Action.Dismiss")) {
// perform your dismiss action
} else if (intent.getStringExtra("action").equals("Action.SetActive")) {
// perform your set active logic
} else {
// handle invalid action
}
}
I solved with this way but still i am not sure it is the right way
public void NotificationSettings(Context context){
Intent stateIntent0 = new Intent(context, MyBroadcastReceiver.class);
Intent stateIntent1 = new Intent(context, MyBroadcastReceiver.class);
stateIntent0.putExtra("id", 100);
stateIntent1.putExtra("id", 200);
PendingIntent pendingIntent0 =
PendingIntent.getBroadcast(context, 0, stateIntent0, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent1 =
PendingIntent.getBroadcast(context, 1, stateIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
builder = new NotificationCompat.Builder(context, "lemubitA")
.setSmallIcon(R.drawable.ic_baseline_add_alert_24)
.setContentTitle("Lemubit Academy Notification")
.setContentText("Hey this is an important notifications")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(R.drawable.ic_baseline_add_alert_24, "Set Active", pendingIntent0)
.addAction(R.drawable.ic_baseline_add_alert_24,"Dismiss", pendingIntent1);
notificationManager = NotificationManagerCompat.from(context);
}
AND this my Broadcast
int notificationId = intent.getIntExtra("id", 0);
Toast.makeText(context, notificationId+"", Toast.LENGTH_SHORT).show();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.cancel(notificationId);

Using startForeground with android service

I have found this Question : How to use startForeground? in Stackoverflow and as it says in the command from the top answer the notification constructor and setLastEventInfo is deprecated. I know that's a duplicated post but the other post is 4 years old and has no answer in the commends so I thought i try do ask it again maybe someone can help me with this.
Code:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
You can use this method. Now with latest API versions you need to set channel for notifications.
private static final String NOTIFICATION_CHANNEL_ID ="notification_channel_id";
private static final String NOTIFICATION_Service_CHANNEL_ID = "service_channel";
.....
private void startInForeground() {
int icon = R.mipmap.icon;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
icon = R.mipmap.icon_transparent;
}
Intent notificationIntent = new Intent(this, CurrentActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.setContentTitle("Service")
.setContentText("Running...");
Notification notification=builder.build();
if(Build.VERSION.SDK_INT>=26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_Service_CHANNEL_ID, "Sync Service", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Service Name");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(this,NOTIFICATION_Service_CHANNEL_ID)
.setContentTitle("Service")
.setContentText("Running...")
.setSmallIcon(icon)
.setContentIntent(pendingIntent)
.build();
}
startForeground(121, notification);
}

notification.setLatestEventInfo() error

Please can you help me, what should I replace .setLatestEventInfo since it gives an error that's can't resolve this method.
This is my code:
if (messages.length > -1) {
Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notifyDetails = new Notification(R.drawable.ic_launcher,"message received",System.currentTimeMillis());
//PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW), 0);
PendingIntent myIntent = PendingIntent.getActivity(context, 0 , defineIntent, 0);
notifyDetails.setLatestEventInfo(context, str, "", myIntent);
notifyDetails.flags = Notification.FLAG_AUTO_CANCEL;
notifyDetails.flags = Notification.DEFAULT_SOUND;
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
Toast.makeText(context, "el rsala " + str, Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(context, EncryptionActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("Encrypt", str);
context.startActivity(i);
This method is now deprecated-
Use this now-:
private NotificationManager mNM;
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence text = getText(R.string.app_name);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = new Notification(R.drawable.ic_notification, null,
System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
Intent pedometerIntent = new Intent();
pedometerIntent.setComponent(new ComponentName(this, Pedometer.class));
pedometerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
pedometerIntent, 0);
builder.setContentTitle("Application");
builder.setSmallIcon(R.drawable.ic_notification);
builder.setContentIntent(contentIntent);
builder.setContentText(text);
/*notification.setLatestEventInfo(this, text,
getText(R.string.notification_subtitle), contentIntent);
*/
mNM.notify(1, builder.build());

How to make notification dissapear after click

I want to make a notification disappear after a click, I don't want to go to new Activity. This is how I build a notification :
public static void getSynchronizeNotification(Context context, DataResponse dataResponse){
Bitmap Largeicon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_SYNCHRONIZE_ID);
Intent in = new Intent(String.valueOf(context));
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, in, 0);
Notification notification = new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.setContentText("Zmiany po synchronizacji...")
.setStyle(new Notification.BigTextStyle().bigText(buildNotificationAfterSynchronizeText(dataResponse)))
.setLargeIcon(Largeicon)
.setAutoCancel(true)
.setVibrate(vibratePattern)
.setSound(alarmSound)
.setPriority(Notification.PRIORITY_MAX)
.build();
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_SYNCHRONIZE_ID, notification);
}
I change this :
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, in, 0);
to
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
and it works

Categories