setting mediaSession with a remote view - java

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

Related

Retrieving notification intent to redirect user to specific activity of the application

I am making an application that gathers push notifications with NotificationListenerService in Android.
Retrieving notification contents such as the name of the app, contents of the app, package name, notification registered time etc. works very well.
However, when trying to retrieve notifications Intent that redirects the user to a specific Activity of an app when clicked, doesnt work. It won't get Intent. What might be the problem?
try {
//ne.cls_intent = getIntent(sbn.getNotification().contentIntent).toString();
ne.cls_intent =getIntent(notification.contentIntent).resolveActivity(pm).getClassName();
} catch (IllegalStateException e) {
ne.cls_intent = "No Intent";
}
Try this, #Hyeon
Intent intent = new Intent(getApplicationContext(), Your_Desired_Activity.class);
intent.putExtra("Key", value); //for sending data to your specific activity if needed.
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), (int) (Math.random() * 100), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "101";
//TODO - make the title BOLD - change the notification icons
mBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
mBuilder.setContentTitle(message_push)
.setSmallIcon(R.drawable.app_logo)
.setContentText(event_title_push)
.setAutoCancel(true)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(getColor(R.color.text_color))
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(event_title_push);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager = getSystemService(NotificationManager.class);
channel.setImportance(importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(channel);
}
assert mNotificationManager != null;
// Cancel the notification after the particular notification gets selected
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify((int) (Math.random() * 100) /* Request Code */, mBuilder.build());
This is the total working of showing the notification with title and vibrate and also redirecting to a specific activity.

How to change the notification settings in android apps?

How can I switch all these settings on programmatically?
I noticed when you install WhatsApp they are all switched on in the beginning(look at the image below).
But I can not find a way to turn them on programmatically.
Here is how I send notifications:
private void sendNotification(Intent intent){
Context context = NotificationService.this;
//open the activity after the notification is clicked
Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent1, 0);
Notification.Builder builder = new Notification.Builder(context)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.drawable.ic_add)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//These are necessary for the notification to pop up
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(Notification.PRIORITY_MAX);
builder.setSound(alarmSound);
builder.setLights(Color.BLUE, 500, 500);
}
//after android O we must use notification channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Reminder to remind to review your notes",
NotificationManager.IMPORTANCE_HIGH);
if(alarmSound != null){
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
channel.setSound(alarmSound,att);
}
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
channel.setDescription("Hello Dear friends"); //this is to test what this is
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setVibrationPattern(new long[]{300, 300, 300});
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
I also added this permission to manifest:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
Update:
Using this code on the emulator, I get the heads-up notification. But on my Xiaomi device, there is no heads-up notification. It just appears on the status bar. If I manually turn on the floating notification (which you can see in the photo) then I will get heads-up notification. But they are switched off by default. When you install Whatsapp they are all switched on.
Is that a kind of privilege for Whatsapp as it is famout? or is there a way to do it?
By default, when you install a app, the system register's default notification channel (on low priority) that doesn't support head up notification by default, it's turned off. You can't control that.
But what you can do it create your own notification channel with highest priority and then register it on app run once.
After that just pass the channel Id with your notification builder so that system shows the head's up notification which you want.
More information can be found here https://developer.android.com/training/notify-user/channels
I have tried for this but unable to set these settings programmatically. Instead of this I have used following method to open notification settings screen to enable notification sounds/vibration.
private void openNotificationSettingsForApp(String channelId) {
// Links to this app's notification settings.
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && channelId!=null){
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID,channelId);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
}
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
startActivity(intent);
}

Android notification channel sound doesn't work

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.

Android: Notification do not generate the default sound

I am trying to generate FCM notifications with sound. I get the notification etc without issues, but there is no sound at all. I am OK with the default sound of notifications. Please check the below code. It is for API 26 and above.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "xxx";
// The user-visible name of the channel.
CharSequence name = "xxx";
// The user-visible description of the channel.
String description = "xxx";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String CHANNEL_ID = "xxx";
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setAutoCancel(true)
.build();
// Issue the notification.
mNotificationManager.notify(new Random().nextInt(), notification);
Why is this happening and how to get the default sound?
Change this part :
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setAutoCancel(true)
.build();
to
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this,"xxx")
.setSmallIcon(R.drawable.volusha_notifications)
.setContentText(text)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.build();
Try using RingtoneManager to get Default Notification Uri as:
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(uri);

How to show just notification count on appview android

I'm new to android. And to show notification on android phones I got this below code
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);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mytune_default)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m /*ID of notification*/ , notificationBuilder.build());
But the thing is I just want that notification unread count on code appview on system, but dont want other things loke message, title etc that appear on notification tray of system. How come this be acheived>
It's not possible to replace launcher icon with widget. You can say to user to place your widget on the home screen, but not in application list. Users must do that in their own. Nevertheless, it's iOs pattern. It's not good idea to bring iOS design elements to android. Android have great notification bar, where user expect to see notification from your app. Android users don't expect to see it over the icon.

Categories