Exception : java.lang.RuntimeException at android.app.ActivityThread.handleReceiver - java

i have an app published in Google play,and i'm stucking with below crash report in Google Console, can anyone help me to understand where this issue came from and how to get resolved.
java.lang.RuntimeException:
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3523)
at android.app.ActivityThread.access$1400 (ActivityThread.java:207)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1759)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:193)
at android.app.ActivityThread.main (ActivityThread.java:6863)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:858)
Caused by: java.lang.IllegalStateException:
at android.support.v4.media.session.MediaButtonReceiver.onReceive
(MediaButtonReceiver.java:124)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3507)
Notification :
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());
}

This will solve in 3 steps.
1:_ Open your build.gradle(Module: app) file.
Add this under the application tag
defaultConfig {
multiDexEnabled true
}
2:_ If you using appcompact then add this line under the dependencies tag
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
else if you migrate your project to AndroidX then add this line
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}
3:_ Open your all activity java files and add MultiDex.intall(contextName)
protected void onCreate(Bundle savedInstanceState) {
MultiDex.install(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mine);
`enter code here`
}

Just add flag to your PendingIntent for Android 12 and above.
Reference

Related

What is causing a RemoteServiceException error?

I am getting a lot of these errors:
android.app.RemoteServiceException:
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1772)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:193)
at android.app.ActivityThread.main (ActivityThread.java:6758)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:497)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:912)
They only seem to happen on Android 8.1, 9, 10 and 11. There's not much else that I can see, it seems to happen on some devices. I've searched everywhere for an answer but nobody seems to know what is causing it exactly. I think it might be something related to the notification channel but maybe not. I tried startForeground() in both onCreate() and onStartCommand() and it doesn't make any difference. I am getting these errors for 5 years in my app and I simply cannot reproduce it on my end. This is my service code:
public static boolean service = false;
public static Context appContext;
public static Handler handler;
public static String notificationText;
#Override
public void onCreate() {
service = true;
appContext = getApplicationContext();
handler = new Handler();
setNotification();
if (notification != null) {
startForeground(1, notification);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public static void setNotification() {
try {
Intent intent = new Intent(appContext, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent intentStop = new Intent(appContext, broadcastReceiver.class);
PendingIntent pIntentStop = PendingIntent.getBroadcast(appContext, 0, intentStop, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new NotificationCompat.Builder(appContext, "X")
.setContentTitle("App Title")
.setContentText(notificationText)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(false)
.setOngoing(true)
.setContentIntent(pIntent)
.addAction(0, "Stop", pIntentStop)
.build();
notification.defaults = 0;
NotificationManager notificationManager = (NotificationManager) appContext.getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("X", "App Title", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{0});
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(1, notification);
}
} catch (Exception e) {
showToast(appContext, e.getMessage());
}
}
public static class broadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.stopService(new Intent(context, MainService.class));
}
}
Does anyone have any clue on what is going on? Thanks!

Android studio notifications implemented but not showing

I have implemented android notifications in android studio. I was creating notification for a media player. following is the function for showing notifications
public void showNotification(int playPauseBtn)
{
Intent intent = new Intent(this, PlayerActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
byte[] picture = null;
try
{
picture = getAlbumArt(listSongs.get(position).getPath());
} catch (Exception ignored)
{
}
Bitmap thumb;
if (picture != null)
{
thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
} else
{
thumb = BitmapFactory.decodeResource(getResources(), R.drawable.icon_music);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_1).setSmallIcon(playPauseBtn)
.setLargeIcon(thumb)
.setContentTitle(listSongs.get(position).getTitle())
.setContentText(listSongs.get(position).getArtist())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPending)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPending)
.addAction(playPauseBtn, "pause", pausePending)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSessionCompat.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(true)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
Toast.makeText(PlayerActivity.this, "Nitification created", Toast.LENGTH_SHORT).show();
}
In the function parameter (playPauseBtn) I am sending the play icon or the pause icon depending upon weather the song is playing or is paused.
Function call is made like following:
showNotification(R.drawable.ic_baseline_pause_24);
OR
showNotification(R.drawable.ic_baseline_play_arrow_24);
But when ever I call this function the notification doesn't show up. I am also using the notification channel but still it is not working. I have also tried to debug the code but the code runs fine, still the notification doesn't show up. please advise
try this.
put this code in your Activity/fragment;
public void getNotification(){
int notifId =new Random().nextInt(500); //get random id
NotificationManager notificationManager;
Notification notification;
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelID = "1";
channelName = "news";
channelDesc = "news description";
NotificationChannel notificationChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(channelDesc);
notificationChannel.enableLights(true);
notificationChannel.setSound(null, null);
notificationChannel.setLightColor(Color.GREEN);
notificationManager.createNotificationChannel(notificationChannel);
}
RingtoneManager.getRingtone(mContext,
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).play();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, channelID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title Of MUSIC")
.setContentText("Content")
.setVibrate(new long[]{100, 500, 500, 500, 500})
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
Intent actionReadMessage = new Intent(mContext, NotifAction.class);
actionReadMessage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
actionReadMessage.setAction("Play");
actionReadMessage.putExtra("NotifId",notifId);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(mContext, notifId, actionReadMessage,PendingIntent.FLAG_CANCEL_CURRENT);
Intent mainAction = new Intent(mContext, NotifAction.class);
mainAction.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAction.setAction("Pause");
mainAction.putExtra("NotifId",notifId);
PendingIntent PausePendingIntent = PendingIntent.getBroadcast(mContext, notifId, mainAction,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(PausePendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Play", playPendingIntent);
builder.addAction(R.mipmap.ic_launcher, "Pause", PausePendingIntent);
notification = builder.build();
notificationManager.notify(notifId, notification);
}
and create class NotifAction.class for handle all action:
public class NotifAction extends BroadcastReceiver {
private static final String TAG = "maybe";
private MediaPlayer mp;
#Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Bundle extra = intent.getExtras();
if (extra != null) {
int notifId = extra.getInt("NotifId");
if (action.equals("Play")) {
mp = MediaPlayer.create(context, R.raw.music);
handleMusicState(mp);
} else if (action.equals("Pause")) {
handleMusicState(mp);
setMessageRead(notifId, context);
} else {
Toast.makeText(context, "extra action !", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Empty extra !", Toast.LENGTH_SHORT).show();
}
}
private void setMessageRead(int id, Context context) {
// other method
clearNotification(id, context);
}
private void clearNotification(int id, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
private void handleMusicState(MediaPlayer mediaPlayer) {
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
else mediaPlayer.start();
}
}
define this receiver to manifest:
note:in tag
<receiver android:name=".NotifAction">
<intent-filter>
<action android:name="Play" />
<action android:name="Pause" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
FIX
Donot use .setMediaSession(mediaSessionCompat.getSessionToken()) in .setStyle() in the code given in the question
simply just use
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle())

MediaStyle : RemoteServiceException: Bad notification posted from package

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

Custom Sound Not Playing Firebase Messaging Android

I am trying to use Custom Notification sound in my android application. I have checked all related questions and answers in stackoverflow but I am not able to figure why its not playing my custom sound in application. My code for notification is like below.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
}
if (remoteMessage.getData().size() > 0) {
sendNotification(remoteMessage.getData().get("title"));
}
}
#Override
public void onNewToken(String token) {
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Context context = getBaseContext();
String channelId = "raj";
int sound_notification = context.getSharedPreferences("setting", MODE_PRIVATE).getInt("sound_notification", 1);
Uri MyCustomSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/raw/sound" + (sound_notification));
//Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageBody)
.setAutoCancel(true)
.setSound(MyCustomSound)
.setContentIntent(pendingIntent);
//notificationBuilder.setSound(MyCustomSound);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Raj",
NotificationManager.IMPORTANCE_HIGH);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0, notificationBuilder.build());
}
}
I have tried to send notification from My Server with PHP as well from Firebase Console but its always play default sound instead my custom sound. Let me know if someone can help me for out from the issue.
Thanks
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/sound/" + R.raw.sound);
mBuilder.setSound(Uri.parse("android.resource://" + getPackageName() + "/sound/" + R.raw.sound));

PendingIntent.getBroadcast not working on for the default notification click/touch event in the notifications drawer - Android Studio 2.3.3 + Java

I have wired up a notifications action handler with PendingIntent.getBroadcast that shows actions inside the notification. The actions work fine, when I use the default click event on the heads up notification it works fine. My issue comes when the notification is in the tray and I have other notifications in the drawer, I am trying to program the default click/touch event on the notification to broadcast to the receiver and run an action. Here is some code:
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
//CLICK ON NOTIFICATION HERE ONLY WORKS ON HEADS UP AND NOT DEFAULT
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class);
notificationIntent.putExtra("visitId", visitId);
notificationIntent.putExtra("link", link);
notificationIntent.setAction(ACCEPT_EXAM);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(clickIntent);
//Accept intent action works fine
Intent acceptExam = new Intent(ctx, PushNotificationActions.class);
acceptExam.setAction(ACCEPT_EXAM);
acceptExam.putExtra("visitId", visitId);
acceptExam.putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent action works fine
Intent dismissExam = new Intent(ctx, PushNotificationActions.class);
dismissExam.setAction(DISMISS_EXAM);
dismissExam.putExtra("visitId", visitId);
dismissExam.putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);
Here is the onReceive method:
private Context context;
#Override
public void onReceive(Context ctx, final Intent intent) {
Log.d("PushNotificationActions","Started");
String action = intent.getAction();
Log.d("<-------------------<<<", "getaction is: " + action);
context = ctx;
if (ACCEPT_EXAM.equals(action)) {
Log.d("ACCEPT_ACTION", "READY FOR EXAM NOW");
Map<String, String> params = new HashMap();
params.put("email", email);
final JSONObject parameters = new JSONObject(params);
Log.d("parameters: ", parameters.toString());
volleyJsonObjectPost("ws", parameters, new Login.ServerCallback() {
public void onSuccess(JSONObject response) {
try {
final JSONObject loginData = response.getJSONObject("d");
DataModel.sharedInstance().key = loginData.getString("key");
final String visitLink; String link; final String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
link = extras.getString("link");
visitId = extras.getString("visitId");
visitLink = link + loginData.getString("key") + ',' + visitId;
JSONObject params = new JSONObject();
params.put("key", loginData.getString("key"));
Log.d("params: ", params.toString());
volleyJsonObjectPost("ws", params, new Login.ServerCallback() {
public void onSuccess(JSONObject result) {
try {
final JSONObject acceptExamResultData = result.getJSONObject("d");
Log.d("acceptExamResultData: ", acceptExamResultData.toString());
if (acceptExamResultData.getBoolean("status") == true) {
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(visitLink));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.android.chrome");
try {
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
} catch (ActivityNotFoundException ex) {
// Chrome browser presumably not installed so allow user to choose instead
intent.setPackage(null);
context.startActivity(intent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}else {
// Exam was already accepted by another Doc
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}else if (DISMISS_EXAM.equals(action)) {
Log.d("DISMISS_ACTION", "I CANNOT TAKE THIS EXAM");
String visitId; Bundle extras = intent.getExtras();
if(extras != null) {
visitId = extras.getString("visitId");
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("Visit ID to cancel", visitId);
mNotificationManager.cancel(Integer.parseInt(visitId));
Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(closeIntent);
}
}
Here is the receiver in the manifest:
<receiver android:name=".PushNotificationActions" >
<intent-filter>
<action android:name="com.Telemed.app.ACCEPT_EXAM" />
<action android:name="com.Telemed.app.DISMISS_EXAM" />
</intent-filter>
</receiver>
Since the notification won't slide easy in the drawer in most cases I need this default functionality to mirror the Accept Exam Action. Only I don't want it to be an action, I just want it to work when the user clicks on the notification. I need to use getBroadcast because I am making a web service call (async) to get some data I need to do the next step
So in order to set the default functionality for the notification you have to create a default pending intent before constructing your notification builder:
Like so:
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Now after that set this:
.setContentIntent(clickIntent)
in the new NotificationCompat.Builder. After that you can set up as many actions as you want but the default will still access your action and act as a default in the case where the drawer sticks your notification at the to and you cannot see your programmed actions.
Uri alertSound = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/page_the_doctor");
//CLICK ON NOTIFICATION
Intent notificationIntent = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent clickIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.telemed_logo)
.setContentTitle("TELEMED PATIENT READY")
.setContentText(notification)
.setDefaults( Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setSound( alertSound )
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(clickIntent)
.setAutoCancel(true);
//Accept intent
Intent acceptExam = new Intent(ctx, PushNotificationActions.class).setAction(ACCEPT_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingAcceptIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), acceptExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.accept_action_24dp, "ACCEPT", pendingAcceptIntent);
//Dismiss intent
Intent dismissExam = new Intent(ctx, PushNotificationActions.class).setAction(DISMISS_EXAM).putExtra("visitId", visitId).putExtra("link", link);
PendingIntent pendingDismissIntent = PendingIntent.getBroadcast(ctx, Integer.parseInt(visitId), dismissExam, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.dismiss_action_24dp, "DISMISS", pendingDismissIntent);
Notification noti = notificationBuilder.build();
noti.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Integer.parseInt(visitId), noti);

Categories

Resources