I am not able to create bigger play/pause button in Decorated notification.
How can I do it?
Here is what I have:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (statusPlay){
notification = new NotificationCompat.Builder(this,FOREGROUND_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_books_mini2)
.setContentTitle(tmpTitle)
.setContentText(""+notificationPercentage + "% " + tmpAuthor)
.setLargeIcon(artwork)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT) //CATEGORY_SERVICE
.addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
.addAction(R.drawable.ic_pause_white,"pause",lPendingPauseIntent)
.addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
.setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
.setShowActionsInCompactView(0,1,2)
.setMediaSession(mediaSession.getSessionToken())
)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setColorized(true)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true);
}else {
notification = new NotificationCompat.Builder(this, FOREGROUND_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_books_mini2)
.setContentTitle(tmpTitle)
.setContentText("" + notificationPercentage + "% " + tmpAuthor)
.setLargeIcon(artwork)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.addAction(R.drawable.prev10w,"prev10",lPendingSeekPrevIntent)
.addAction(R.drawable.ic_play_arrow_white,"play",lPendingPlayIntent)
.addAction(R.drawable.next10w,"next10",lPendingSeekNextIntent)
.setStyle(new androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
.setShowActionsInCompactView(0,1,2)
.setMediaSession(mediaSession.getSessionToken())
)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setColorized(true)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true)
;
;
}
}
This looks like this with small buttons on bottom:
But required is this bigger button:
In official poages of android development ,they recommend to use this Decorated Media Custom View in notifications due to restricted space and colors to be visible with texts. Many thanks for help.
Related
I'm trying to create an app with 3 different notification sounds (But not different notification channels), I create custom notification sound, but when I try to change the sound, it stays still the same, I also tried to delete the channel and create it again but notification sound does not change.
First I create Channel:
String CHANNEL_ID = Constants.notification_channel_ID;
int NOTIFICATION_ID = 1991;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel existingChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
if (existingChannel != null){
mNotificationManager.deleteNotificationChannel(CHANNEL_ID);
}
CharSequence name = getResources().getString(R.string.drink_reminder);
String description = getResources().getString(R.string.notification_to_remind_you_to_drink);
int importance = NotificationManager.IMPORTANCE_HIGH;
if (s1 = true){
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound);
}else{
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound1);
}
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION ).setUsage(AudioAttributes.USAGE_NOTIFICATION).build() ;
NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID , name , importance) ;
notificationChannel.setDescription(description);
notificationChannel.enableLights(true) ;
notificationChannel.setLightColor(Color.BLUE) ;
notificationChannel.enableVibration( tinyDB.getBoolean(Constants.settings_notification_vibration_key,true));
notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;
notificationChannel.setSound(sound , audioAttributes) ;
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
Then I create Notifiaction:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(this.getResources().getString(R.string.text))
.setContentIntent(pendingIntent)
.setSound(sound)
.setChannelId(CHANNEL_ID)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
So on first time this code works, when later on I call this method again to and change the sound, notifications are still working with same sound like in beginning, also I can't disable, enable vibration (It stays the same like first time is configured). As you see I'm also trying to recreate notification channel, but still the same.
Any help will be appriciated.
Resolved by setting up a silent notification and adding manual sound and vibration.
So on When I create Channel I use:
notificationChannel.enableVibration(false);
notificationChannel.setSound(null,null);
Also when I build notification I add this code:
.setSilent(true)
Than to vibrate I use this:
private void vibrate (Context context){
Vibrator v = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
}
and for notification ringtone I use this code:
private void playSound(Context context, String SoundUri){
Uri rawPathUri = Uri.parse(SoundUri);
Ringtone r = RingtoneManager.getRingtone(context, rawPathUri);
r.play();
}
When SoundUri is the String that matches the sound from settings user have choosen.
I have the following setup for a media style notification:
NotificationCompat.Builder nc = new NotificationCompat.Builder(this, CHANNEL_ID);
NotificationManager nm = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.drawable.play);
nc.setAutoCancel(true);
nc.setCustomBigContentView(view);
nc.setContentTitle("MusicPlayer");
nc.setPriority(NotificationCompat.PRIORITY_MAX);
nc.setContentText("Control AUdio");
Notification notification = nc.build();
notification.flags = NotificationCompat.FLAG_ONGOING_EVENT|NotificationCompat.FLAG_FOREGROUND_SERVICE
| NotificationCompat.FLAG_NO_CLEAR;
view.setOnClickPendingIntent(R.id.notif_play, playbackAction(0));
view.setOnClickPendingIntent(R.id.notif_next, playbackAction(2));
view.setOnClickPendingIntent(R.id.notif_previous, playbackAction(3));
but, I don't know how to add a MediaSession to this. The only way I knew was:
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compact notification view.
.setShowActionsInCompactView( 1, 2))
but, this really messes up the RemoteView, how can I add a MediaSession while retaining the RemoteView
I don't know why but no matter what I change the mp3 sound in raw file, the notification just make one sound that its name is the least alphabet, ex: My raw file, the notification will play message_tone no matter what I change the name in the code:
/// Set sound for channel
notificationChannel.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.sneeze), null);
My code for set up channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/// Set channel's ID, name, and importance
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_TEST,
"OUTFITTERX",
NotificationManager.IMPORTANCE_HIGH
);
/// Set sound for channel
notificationChannel.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.sneeze), null);
// 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(notificationChannel);
}
And show notification:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification notification = new Notification.Builder(this, CHANNEL_TEST)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(message)
.setPriority(Notification.PRIORITY_HIGH)
.build();
/// Show the notification
notificationManager.notify(0, notification);
}
UPDATE
My code for android version lower than android O
/// Create a Notification Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_TEST)
.setSmallIcon(R.drawable.logo) /// Set notification's icon
.setSound(Uri.parse("android.resource://" + getPackageName() + '/' + R.raw.tuturu)) /// Set sound
.setAutoCancel(true) /// Automatically remove notification when user taps it
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) /// Set sound vibration
.setOnlyAlertOnce(true) /// Only alert Once
.setContentIntent(pendingIntent) /// Set intent it will show when click notification
.setContent(getCustomDesign(title, message)); /// Set the design of notification
notificationManager.notify(0, builder.build());
And I use android Pie 9.0 to test
I'm guessing that this could be because you can not edit a NotificationChannel once created. I think once created it will keep the original configuration (the one used when first creating it). To make it work you will need to delete the app (unistall it) and re install it with the new settings, I mean the new sound file.
I am implementing Notifications in android. I want to change the icon of notification, but the problem is that setSmallIcon is not working. My custom icon is showing in the lollipop device but not showing the custom icon above lollipop devices.
I have tried the following code:
send_notification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.book2);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.drawable.ic_notification);
} else {
builder.setSmallIcon(R.drawable.notification);
}
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
The big picture is also not showing. Please Help.
EDIT:
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.test);
String channelId = getString(R.string.default_notification_channel_id);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
if (remoteMessage.getData().size() > 0) {
String title = remoteMessage.getData().get("title");
String text = remoteMessage.getData().get("body");
builder.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(text)
.setLargeIcon(icon)
.setPriority(Notification.PRIORITY_MAX)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigLargeIcon(icon));
} else if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String text = remoteMessage.getNotification().getBody();
builder.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(text)
.setLargeIcon(icon)
.setPriority(Notification.PRIORITY_MAX)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigLargeIcon(icon));
}
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Testing channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(notificationChannel);
}
manager.notify(1, builder.build());
Try uninstalling and reinstalling the 100% fresh App. Android keeps cache so things work more quickly and the notification is one of those things.
Uninstalling and reinstalling worked for my issue some time ago.
Also do remember that in Android Oreo and above, in order for notifications to work; notification channels must be created and also the notification that you're creating should be assigned to one of them.
EDIT
What I've tried (and it works for me): (Sample in Kotlin but should be similar enough);
fun onClick(view: View) {
var icon_resource = R.drawable.ic_mtrl_chip_close_circle
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
icon_resource = R.drawable.ic_mtrl_chip_checked_circle
}
val icon = BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher_round)
val notification = NotificationCompat.Builder(this)
.setSmallIcon(icon_resource)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setLargeIcon(icon)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null)).build()
val manager= getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1,notification)
}
SECOND EDIT
I think there's a problem with your image, (as there was in mine; sizes or something). After spending a lot of time trying to figure out why it didn't display the launcher icon in the notifications I decided to try with one of my images that I had laying around...
Tested with Android O; API 28
And here are the results:
Feel free to try with the original image I used:
Here's the code that is powering these results; it's not very different from the first one...
// Parametherise this drawable with an if statement of your own
var icon_resource = R.drawable.ic_mtrl_chip_close_circle
val manager= NotificationManagerCompat.from(this)
// This is required because the testing device is an Android O
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(
NotificationChannel("CUSTOM_NOTIFICATIONS", "StackOverflow", NotificationManager.IMPORTANCE_HIGH)
)
}
val icon = BitmapFactory.decodeResource(resources,R.mipmap.dafuq)
val notification = NotificationCompat.Builder(this, "CUSTOM_NOTIFICATIONS")
.setSmallIcon(icon_resource)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setLargeIcon(icon)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null)).build()
manager.notify(1,notification)
Additional info:
When I'm using a wrong image, I get this pesky log in my Logcat. Check for the same or similars!
2019-04-10 20:11:02.120 3434-3434/com.example.deletemeapp D/skia: --- Failed to create image decoder with message 'unimplemented'
What you want to do is create the notification icon as follows:
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("New Book Added")
.setContentText("Android with java");
Now Add:
NotificationCompat.BigPictureStyle s = new NotificationCompat.BigPictureStyle().bigPicture(bitmap_image);
s.setSummaryText("Summary text appears on expanding the notification");
//Set the style of the notification to this big picture style
builder.setStyle(s);
For the versioning add this:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
// Marshmallow+
}else{
//below Marshmallow
}
Hope this helps :)
I'm trying to change setLightColor with a colour returned from a JavaScript Interface. Unfortunately, NotificationCompat.Builder(context, CHANNEL_ID).setLights has absolutely no sway on API >= 26, so I can't use Intent.putExtra or anything similar.
Is it even possible to change it after it's already been set? I would like it to be dynamic.
EDIT There seems to be some misconception on what I want. I don't want to touch the Broadcast Reciever. It works just fine. I want to change the notification channel. It's not updating setLightColor(Color.___).
In protected void onCreate
String jobColor = someColor; // Will be filled in by other code - different colour every time
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel_Name";
String description = "Channel_Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(Color.parseColor(jobColor)); // Dynamically set from above
channel.enableVibration(true);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
My BroadcastReciever - setLight is not applicable for API 26 or higher I believe
public class AlarmReceiver extends BroadcastReceiver {
private final String CHANNEL_ID = "some_channel";
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 , new Intent(context, MainPage.class), 0);
String jobColor = intent.getStringExtra("jobColor");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("Upcoming Shift!")
.setContentText("Shift at " + intent.getStringExtra("jobName") + " on " + intent.getStringExtra("jobDate") + " at " + intent.getStringExtra("jobTime"))
.setStyle(new NotificationCompat.BigTextStyle().bigText("You have a shift at " + intent.getStringExtra("jobName") + " on " + intent.getStringExtra("jobDate") + " at " + intent.getStringExtra("jobTime")))
.setLights(Color.parseColor(jobColor), 10000, 1000)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(12345, mBuilder.build());
}
}
You can't change channel color notification, importance etc. programmatically without deleting the channel.
Because a user may have changed the light color manually.
To achieve this programmatically to get the channel and create a new channel with a new id. delete the old channel. Your changes will not reflect if create a channel with the previous id
for reference check WhatsApp application try to change the ringtone from an application and see in a channel at the bottom left x channel is deleted message
Source Android Doc
From createNotificationChannel() description:
This can also be used to restore a deleted channel and to update an existing channel's
* name, description, group, and/or importance.
So you can try this:
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//find created channel
NotificationChannel channel = notificationManager.getNotificationChannel("id");
if (channel != null){
//set new color
channel.setLightColor(0);
//update channel
notificationManager.createNotificationChannel(channel);
}