After loading in all the current song information to the session metadata, the album art refuses to load on the lockscreen. I know for a fact that the bitmap is valid because I use the same resource for the notification art. I've also tried using just a static resource, but no luck. Any help would be much appreciated.
String more;
if (shuffled) {
more = Integer.toString(shufflePosition+1) + "/" + Integer.toString(playlist.size());
}
else{
more = Integer.toString(position+1) + "/" + Integer.toString(playlist.size());
}
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
//Build a new notification according to the current state of the MediaPlayer
if (mp.isPlaying()) {
notificationAction = android.R.drawable.ic_media_pause;
} else{
notificationAction = android.R.drawable.ic_media_play;
}
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),np.getArt());
} catch (IOException e) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.mipmap.empty_track);
e.printStackTrace();
}
mSession.setMetadata(new MediaMetadataCompat.Builder()
.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap)
.putString(MediaMetadata.METADATA_KEY_ARTIST, np.getArtist())
.putString(MediaMetadata.METADATA_KEY_ALBUM, np.getAlbum())
.putString(MediaMetadata.METADATA_KEY_TITLE, np.getTrack())
.build());
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notification = new android.support.v7.app.NotificationCompat.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.mipmap.empty_artist)
.setShowWhen(false)
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_previous, "Previous", pendingPrev).build())
.addAction(new NotificationCompat.Action.Builder(notificationAction, "Pause", pendingPlay).build())
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_next, "Next", pendingNext).build())
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(np.getTrack())
.setContentText(np.getArtist())
.setSubText(more)
.setPriority(Notification.PRIORITY_MAX)
.setLargeIcon(bitmap)
.setContentIntent(launchActivity)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
.setMediaSession(mSession.getSessionToken()).setShowActionsInCompactView(0,1,2))
.build();
} else {
notification = new android.support.v7.app.NotificationCompat.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.mipmap.empty_artist)
.setShowWhen(false)
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_previous, "Previous", pendingPrev).build())
.addAction(new NotificationCompat.Action.Builder(notificationAction, "Pause", pendingPlay).build())
.addAction(new NotificationCompat.Action.Builder(android.R.drawable.ic_media_next, "Next", pendingNext).build())
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(np.getTrack())
.setContentText(np.getArtist())
.setSubText(more)
.setPriority(Notification.PRIORITY_MAX)
.setLargeIcon(bitmap)
.setContentIntent(launchActivity)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
.setMediaSession(mSession.getSessionToken())
.setShowActionsInCompactView(0,1,2))
.build();
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(001, notification);
startForeground(001, notification);
As per the Working with a Media Session documentation page:
In Android 4.0 (API level 14) and greater, the background of the lock screen displays your album artwork - but only if the media session metadata includes a background bitmap.
You must set a background Bitmap in your MediaMetadataCompat by using putBitmap with either METADATA_KEY_ALBUM_ART or METADATA_KEY_ART
You have to use playbackstate after 3 days i found this one
public void pausePlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
startForeground(false);
((MainActivity) context).notificationUpdated(false);
isPlay = false;
playbackStateCompat.setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_STOP);
playbackStateCompat.setState(PlaybackStateCompat.STATE_PAUSED, mediaPlayer.getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
mediaSession.setPlaybackState(playbackStateCompat.build());
}
}
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.parse(currentSong.getUrl()));
mediaSession.setMetadata(getMetadata());
playbackStateCompat.setActions(PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_STOP);
playbackStateCompat.setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
mediaSession.setPlaybackState(playbackStateCompat.build());
mediaPlayer.start();
Related
I have been trying showing heads up notification as part of Full Screen Intent. It works well in some devices and if device is not locked, it shows up as heads up notification.
But in samsung devices, i have set system notification setting to brief (that shows notification for brief amount of time and then disappear back to system tray). This setting causing heads up notification to appear for small amount of time.
For the same setting, whatsapp and system caller app able to show heads up notification for incoming call.
i have used the following code
Channel creation
private void createFullIntentChannel(){
NotificationManager manager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3" ) ;
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
String NOTIFICATION_CHANNEL_ID = "com.myapp.app.fullintent";
String channelName = "FullRide";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.enableVibration(true);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(sound, attributes);
chan.setShowBadge(true);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(chan);
}
}
Setting content and action buttons on notification
public void showFullScreenIntent(final int notifId, String pickLoc, String dropLoc, String tripType, String accountID, String accountType,
String qrMode, Integer stopCount, Integer vhclType, String estInfo) {
setMediaPlayerFile();
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
PlayFile();
}
});
PlayFile();
}
// set content pending intent
Intent fullScreenIntent = new Intent(ctx, NewRideRequest.class);
fullScreenIntent.putExtra("Action", "UserChoice");
fullScreenIntent.putExtra("ID", notifId);
fullScreenIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent contentIntent = PendingIntent.getActivity(ctx, ACTION_USER_REQUEST_ID,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button accept pending intent
Intent acceptIntent = new Intent(ctx, NewRideRequest.class);
acceptIntent.putExtra("Action", "Accept");
acceptIntent.putExtra("ID", notifId);
acceptIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingAcceptIntent = PendingIntent
.getActivity(ctx, ACTION_INTENT_REQUEST_ID, acceptIntent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// set action button reject pending intent
Intent rejectIntent = new Intent(ctx, NotificationAction.class);
rejectIntent.putExtra("Action", "Reject");
rejectIntent.putExtra("ID", notifId);
rejectIntent.putExtra("BookingID", String.valueOf(notifId));
PendingIntent pendingRejectIntent = PendingIntent
.getBroadcast(ctx, ACTION_INTENT_REQUEST_ID, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + ctx.getPackageName() + "/raw/new_ride.mp3") ;
createFullIntentChannel();
String val = dbHelper.GetVehicleMaster(dbHelper.getReadableDatabase(), vhclType);
// set notification builder
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(ctx, "com.myapp.app.fullintent")
.setSmallIcon(R.drawable.ic_yego_logo)
.setContentTitle("New " + (val.contains(",") ? val.split(",")[0] : "") + " Ride Request")
.setContentText(getContent(stopCount, pickLoc, dropLoc))
//.setSound(sound)
.setOngoing(true)
.setTimeoutAfter(10000)
.setDefaults(Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND)
.addAction(R.drawable.payment_success_1, getActionText(R.string.txt_accept, R.color.colorGreen), pendingAcceptIntent)
.addAction(R.drawable.payment_failed_1, getActionText(R.string.txt_reject, R.color.colorRed), pendingRejectIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setFullScreenIntent(contentIntent, true);
Notification incomingCallNotification = notificationBuilder.build();
incomingCallNotification.sound = sound;
//incomingCallNotification.flags = Notification.FLAG_INSISTENT;
final NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notifId, incomingCallNotification);
Handler handler = new Handler(Looper.getMainLooper());
long delayInMilliseconds = 10000;
handler.postDelayed(new Runnable() {
public void run() {
try {
Log.e("MyApp", "Handler runs");
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
notificationManager.cancel(notifId);
}catch (Exception e){
}
}
}, delayInMilliseconds);
}
Please suggest how can i set ongoing heads up notification to be on screen regardless of system setting of notification.
Creating Notification Channel
before i create channel i am deleting old channel with channel id.
public class App extends Application {
public static String CHANNEL_ID = "CH1";
public static String CHANNEL_NAME = "CH1 Channel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
public void createNotificationChannel()
{
PrefManager prefManager = PrefManager.getPrefManager(this);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
Uri defaultUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
AudioAttributes attr = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
if (prefManager.getNotificationSound().equals("Bell")) {
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + getPackageName() + "/" + R.raw.bells);
channel.setSound(alarmSound, attr);
} else {
channel.setSound(defaultUri, attr);
}
channel.enableLights(true);
channel.enableVibration(true);
assert notificationManager != null;
//Deleting Notification Channel
try
{
notificationManager.deleteNotificationChannel(channel.getId());
} catch (Exception E) {}
notificationManager.createNotificationChannel(channel);
}
}
}
Posting Notification by using below.
Uri defaultUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + context.getPackageName() + "/" + R.raw.bells);
Notification notification = new NotificationCompat.Builder(context, App.CHANNEL_ID)
.setContentTitle(description)
.setContentText(notificationMessageArray[randomIndex])
.setSmallIcon(R.drawable.ic_buddha)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound((PrefManager.getPrefManager(context).getNotificationSound().equals("Bell") ? alarmSound : defaultUri), AudioManager.STREAM_NOTIFICATION)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.build();
Log.e(TAG, "Posting Notification " + description);
notificationManager.notify(new Random().nextInt() * 100, notification);
before i create channel i am deleting old channel with channel id.
I dont know where i am going wrong in this code.
if i remove code of setting sound from channel and notification default sound not playing but other notification has sound!. i tried with changing importent HIGH to DEFAULT but still same result.
setSound is only set the ringtone. Just add setOnlyAlertOnce(true), so your code will look like this :
Notification notification = new NotificationCompat.Builder(context, App.CHANNEL_ID)
.setContentTitle(description)
.setContentText(notificationMessageArray[randomIndex])
.setSmallIcon(R.drawable.ic_buddha)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound((PrefManager.getPrefManager(context).getNotificationSound().equals("Bell") ? alarmSound : defaultUri), AudioManager.STREAM_NOTIFICATION)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setOnlyAlertOnce(true)
.build();
Check the documentation for the detail
The uri has a value when debugging, but set.sound does't work and does't run the sound program.
private void notification(){
uri = intent.getData();
int notifictionId = 1;
Notification.Builder Builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.eye_rest)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.eye_rest))
.setContentTitle("Eye rest")
.setContentText("It's time to rest the eyes")
.setAutoCancel(true)
.setVibrate(new long[] { 600, 600 })
.setSound(uri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "YOUR_CHANNEL_ID";
NotificationChannel channel = new NotificationChannel(channelId,"Channel human readable title",NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(Color.BLUE);
channel.setSound(uri,null);
Builder.setVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
Builder.setChannelId(channelId);
}
notificationManager.notify(notifictionId, Builder.build());
And I select the sound from the phone's ringtone list by this code :
intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
uri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE );
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Choose a song for notification");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
startActivity(intent);
I'm trying to create a notification media controller in my app using the code below which is working fine on all devices expect Huawei P8 Lite with Android 5.0 , I get this error log from Firebase Test Lab :
android.app.RemoteServiceException: Bad notification posted from
package maa.app_app: Couldn't expand RemoteViews for:
StatusBarNotification(pkg=maa.app_app
user=UserHandle{0} id=555 tag=null score=10
key=0|maa.app_app|555|null|10108: Notification(pri=1
contentView=maa.app_app/0x109007f vibrate=null
sound=null defaults=0x0 flags=0x62 color=0xffbfbfbf category=transport
actions=2 vis=PUBLIC)) FATAL EXCEPTION: main Process:
maa.app_app, PID: 18793
android.app.RemoteServiceException: Bad notification posted from
package maa.app_app: Couldn't expand RemoteViews for:
StatusBarNotification(pkg=maa.app_app
user=UserHandle{0} id=555 tag=null score=10
key=0|maa.app_app|555|null|10108: Notification(pri=1
contentView=maa.app_app/0x109007f vibrate=null
sound=null defaults=0x0 flags=0x62 color=0xffbfbfbf category=transport
actions=2 vis=PUBLIC)) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1534)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5538) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
here's my code :
void startNotify(Context context, String playbackStatus, String title) {
String titlesonge;
String artist;
try {
titlesonge = StringUtils.substringBefore(title, " - ");
artist = StringUtils.substringAfter(title, " - ");
} catch (Exception e) {
titlesonge = title.substring(0, title.indexOf(" - "));
artist = title.substring(title.lastIndexOf(" - ") - 1);
}
int icon = R.drawable.ic_pause_white;
Intent playbackAction = new Intent(service, RadioService.class);
playbackAction.setAction(RadioService.ACTION_PAUSE);
PendingIntent action = PendingIntent.getService(service, 1, playbackAction, 0);
if (playbackStatus.equals(PlaybackStatus.PAUSED)) {
icon = R.drawable.ic_play_white;
playbackAction.setAction(RadioService.ACTION_PLAY);
action = PendingIntent.getService(service, 2, playbackAction, 0);
}
Intent stopIntent = new Intent(service, RadioService.class);
stopIntent.setAction(RadioService.ACTION_STOP);
PendingIntent stopAction = PendingIntent.getService(service, 3, stopIntent, 0);
Intent intent = new Intent(service, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(service, 0, intent, 0);
notificationManager.cancel(NOTIFICATION_ID);
String PRIMARY_CHANNEL = "PRIMARY_CHANNEL_ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
String PRIMARY_CHANNEL_NAME = "PRIMARY";
NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, PRIMARY_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(service, PRIMARY_CHANNEL)
.setAutoCancel(false)
.setContentTitle(titlesonge)
.setContentText(artist)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.largeicon))
.setContentIntent(pendingIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.smallwidth)
.setColor(ContextCompat.getColor(context, R.color.colorneeded))
.addAction(icon, "pause", action)
.addAction(R.drawable.ic_stop_white, "stop", stopAction)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setWhen(System.currentTimeMillis())
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
.setMediaSession(service.getMediaSession().getSessionToken())
.setShowActionsInCompactView(0, 1)
.setShowCancelButton(true)
.setCancelButtonIntent(stopAction));
service.startForeground(NOTIFICATION_ID, builder.build());
}
can anyone help me to get resolved this issue
For some reason, Huawei devices with Android 5.0 crashes when using .setStyle() method so you have two possibilities :
1 - detect device Manufacture if is Huawei or not, and have an Android 5.0 or below or not
public boolean isLolliPopHuawei() {
return (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 ||
android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) && Build.MANUFACTURER.equalsIgnoreCase("HUAWEI");
}
2 - Use PlayerNotificationManager instead
void exoPlayerNotification(Context context, SimpleExoPlayer exoPlayer, String title) {
String titlesonge;
String artist;
try {
titlesonge = StringUtils.substringBefore(title, " - ");
artist = StringUtils.substringAfter(title, " - ");
} catch (Exception e) {
titlesonge = title.substring(0, title.indexOf(" - "));
artist = title.substring(title.lastIndexOf(" - ") - 1);
}
String finalArtist = artist;
String finalTitlesonge = titlesonge;
mPlayerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(
context,
"PRIMARY_CHANNEL_ID",
R.string.plaza,
NOTIFICATION_ID,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public String getCurrentContentTitle(Player player) {
return finalArtist;
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(service, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return PendingIntent.getActivity(service, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
#Override
public String getCurrentContentText(Player player) {
return finalTitlesonge;
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return BitmapFactory.decodeResource(service.getResources(), R.drawable.largeicon);
}
#Nullable
#Override
public String getCurrentSubText(Player player) {
return null;
}
}
);
mPlayerNotificationManager.setUseNavigationActions(false);
mPlayerNotificationManager.setFastForwardIncrementMs(0);
mPlayerNotificationManager.setRewindIncrementMs(0);
mPlayerNotificationManager.setColorized(true);
mPlayerNotificationManager.setColor(0xFFEEEEEE);
mPlayerNotificationManager.setUseChronometer(true);
mPlayerNotificationManager.setOngoing(true);
mPlayerNotificationManager.setPriority(NotificationCompat.PRIORITY_MAX);
mPlayerNotificationManager.setUsePlayPauseActions(true);
mPlayerNotificationManager.setSmallIcon(R.drawable.smallwidth);
mPlayerNotificationManager.setNotificationListener(new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationStarted(int notificationId, Notification notification) {
service.startForeground(notificationId, notification);
}
#Override
public void onNotificationCancelled(int notificationId) {
service.stopSelf();
cancelNotify();
}
});
mPlayerNotificationManager.setPlayer(exoPlayer);
}
Since some Huawei devices don't support MediaStyle you need to build notification without styling. I experienced this issue on this models Huawei P8 Lite and Huawei Y3II. So, check if device is huawei and SDK versions as mentioned and create a simple notification as below. This question helped me to find solution Strange allow/deny question on Huawei 5.1 phone when showing notification
. Anyway, I hope helps someone
boolean isLollipopHuawei = (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 ||
android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) && Build.MANUFACTURER.equalsIgnoreCase("HUAWEI");
if (isLollipopHuawei) {
builder
.setContentTitle(description.getTitle())
.setContentText(contentText)
.setOngoing(true)
.setContentIntent(createContentIntent())
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.mobi_plc))
.addAction(R.drawable.ic_previous_outline_notification,
this.service.getString(R.string.next_station),
MediaButtonReceiver.buildMediaButtonPendingIntent(
this.service,
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS))
.addAction(R.drawable.ic_next_outline_notification,
this.service.getString(R.string.next_station),
MediaButtonReceiver.buildMediaButtonPendingIntent(
this.service,
PlaybackStateCompat.ACTION_SKIP_TO_NEXT))
.setSmallIcon(R.drawable.ic_stat)
.setAutoCancel(false);
}
I had the same issue and the root cause was not able to setStyle, it was only giving this exception in Huawei P8 Lite, not on other devices.
So, what i had to do was check if current device is android version 5.0 and its manufacturer is Huawei and remove the setStyle property. please check below code
boolean isLollipopHuawei = (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 ||
android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) && Build.MANUFACTURER.equalsIgnoreCase("HUAWEI");
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 || Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
if (isLollipopHuawei) {
return builder
.addAction(generateAction(android.R.drawable.ic_media_previous, "Previous", Constants.ACTION_PREVIOUS))
.addAction(action)
.addAction(generateAction(android.R.drawable.ic_media_next, "Next", Constants.ACTION_NEXT))
.setSmallIcon(R.mipmap.vpicon_grayscale)
.setContentTitle(getSongDataHelper().getTitle())
.setContentIntent(pendingIntent)
.setContentText(getSongDataHelper().getAlbum())
.setLargeIcon(getSongDataHelper().getAlbumArt())
//.setColor(color)
/* .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setMediaSession(mMediaSession.getSessionToken()))*/
.build();
} else {
return builder
.addAction(generateAction(android.R.drawable.ic_media_previous, "Previous", Constants.ACTION_PREVIOUS))
.addAction(action)
.addAction(generateAction(android.R.drawable.ic_media_next, "Next", Constants.ACTION_NEXT))
.setSmallIcon(R.mipmap.vpicon_grayscale)
.setContentTitle(getSongDataHelper().getTitle())
.setContentIntent(pendingIntent)
.setContentText(getSongDataHelper().getAlbum())
.setLargeIcon(getSongDataHelper().getAlbumArt())
//.setColor(color)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setMediaSession(mMediaSession.getSessionToken()))
.build();
}
}
I am sending push notification from google firebase for my android app with target of Android 5.0:
My push notification code is:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String badge = "0";
Uri uri = Uri.parse(
getString(R.string.app_host_name)
);
Map<String, String> data = remoteMessage.getData();
if (data.size() > 0) {
try {
uri = Uri.parse(
data.get("link")
);
badge = data.get("badge");
} catch (NullPointerException e) {
//
}
}
if (remoteMessage.getNotification() != null) {
RemoteMessage.Notification notification = remoteMessage.getNotification();
sendNotification(notification.getTitle(), notification.getBody(), uri.toString(), badge);
}
}
private void sendNotification(String title, String body, String url, String badge) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (Patterns.WEB_URL.matcher(url).matches()) {
intent.putExtra("link", url);
}
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
Resources resources = getApplicationContext().getResources();
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "default")
.setColor(
resources.getColor(R.color.colorPrimaryDark)
)
.setSmallIcon(
R.drawable.ic_stat_icon
)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setNumber(Integer.parseInt(badge))
.setLargeIcon(
BitmapFactory.decodeResource(
resources,
R.mipmap.ic_launcher
)
)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel notificationChannel = new NotificationChannel(
"default",
"Main notification channel",
NotificationManager.IMPORTANCE_HIGH
);
notificationManager.createNotificationChannel(
notificationChannel
);
}
notificationManager.notify(
1,
notificationBuilder.build()
);
}
And everything is super perfect when application is active/opened/not in background, but when it is not, notifications are not grouped, there is no number displayed, and no reaction on all of this settings at all, what i was able to change is only small icon and circle color via manifest settings
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_icon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorPrimaryDark" />
but why? It's like when app is in background notifications are not using settings from Activity code but using only some kind of "default" one from AndroidManifest.
As you said in the comments:
when app is on background, app isn't taking setNumber, setAutoCancel, setSmallIcon, setLargeIcon options
It is because you are using notification payload to send the notification which only triggers on the foreground.
So when your app is in the background it does not enter this method.
to solve this you can use data payload alone:
"data": {
"titles": "New Title",
"bodys": "body here"
}
since the data payload will enter the onMessageReceived() when your app is in foreground/background.
then in fcm you can do this:
if (remoteMessage.getData().size() > 0) {
title = remoteMessage.getData().get("titles");
body = remoteMessage.getData().get("bodys");
}