152

I'm seeing the following exception in crash logs:

android.app.RemoteServiceException: Bad notification posted from package com.my.package: Couldn't create icon: StatusBarIcon(pkg=com.my.package user=0 id=0x7f02015d level=0 visible=true num=0 )
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1456)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5487)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)

I'm posting my Notification from an IntentService from a PendingIntent set via the AlarmManager using the following method. All values passed in here are from the bundle extras in the PendingIntent / IntentService.

/**
 * Notification 
 *
 * @param c
 * @param intent
 * @param notificationId
 * @param title
 * @param message
 * @param largeIcon
 * @param smallIcon
 */
public static void showNotification(Context c, Intent intent,
        int notificationId, String title, String message, int largeIcon,
        int smallIcon) {
    PendingIntent detailsIntent = PendingIntent.getActivity(c,
            notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // BUILD
    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            c);
    // TITLE
    mNotifyBuilder.setContentTitle(title).setContentText(message);

    // ICONS
    mNotifyBuilder.setSmallIcon(smallIcon);
    if (Util.isAndroidOSAtLeast(Build.VERSION_CODES.HONEYCOMB)) {
        Bitmap large_icon_bmp = ((BitmapDrawable) c.getResources()
                .getDrawable(largeIcon)).getBitmap();
        mNotifyBuilder.setLargeIcon(large_icon_bmp);
    }

    mNotifyBuilder.setContentIntent(detailsIntent);
    mNotifyBuilder.setVibrate(new long[] { 500, 1500 });
    mNotifyBuilder.setTicker(message);
    mNotifyBuilder.setContentText(message);

    // NOTIFY
    NotificationManager nm = (NotificationManager) c
            .getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(notificationId, mNotifyBuilder.build());
}

From what I've seen of other answers - the exception I'm seeing happens when setSmallIcon() is not called properly.

I've checked and double checked that the Resource IDs being passed are all correct.

Sufian
  • 6,405
  • 16
  • 66
  • 120
FishStix
  • 4,994
  • 9
  • 38
  • 53
  • 3
    I'm experiencing the same error (crash reports from a live app). I can't reproduce it on my device. I'm currently thinking it's because people modified the .apk – darken Sep 07 '14 at 21:52
  • Guys, in which way can I solve this problem. I use pngs, but very rarely app crashes – Roman Soviak Feb 27 '18 at 16:43

26 Answers26

113

What was happening was, I was including the integer reference to the icon in the PendingIntent bundle, and that integer was later being referenced while being posted to the NotificationManager.

In between getting the integer reference and the pending intent going off, the app was updated and all of the drawable references changed. The integer that used to reference the correct drawable now referenced either the incorrect drawable or none at all (none at all - causing this crash)

FishStix
  • 4,994
  • 9
  • 38
  • 53
  • 12
    Bizarre. In other words, this isn't fixable is it? I'm seeing the same crashes in my app. – mxk Oct 05 '14 at 17:03
  • It does not seem fixable. I will, in the future, have to devise a different way to go about posting notifications with images in the future.... – FishStix Oct 06 '14 at 23:44
  • What if we try to set the textSize of the remote view as ret.setInt(id, "setTextSize", 20); It also crashes. I know we also have to provide the units, but how do I do that with such method signature. Any pointer?? – bitsabhi Jan 28 '16 at 09:30
  • I have the same problem. Currently researching the possibility of using a custom view utilizing the RemoteViews.ActionException in order to handle the exception raised in this scenario. I'll report if I find a way to make it work. Another approach is to get the drawables used in the notification to get the same ID under R.drawable when compiling so that the icon get the same ID in subsequent builds (but I still haven't figured out how to do it and wether it's even possible). – FunkSoulBrother Jul 18 '16 at 19:34
  • 2
    Could it be possible to clear the notification and everything related when the app is killed to be updated? (Assuming that would make the app avoid the issue) – NoHarmDan Dec 01 '16 at 14:08
  • 4
    In case you want to reference R.drawable.my_image, it's safer to save it to bundle as a string( `bundle.putString("img", "my_image")`and then convert when needed to actual @DrawableRes integer as follows: `ctx.resources.getIdentifier(bundle.getString("img"), "drawable", ctx.packageName)` – vanomart Jan 11 '17 at 13:04
  • Please can you show us what you were doing in code? Not sure what you mean by 'integer reference' - aren't they all integer references? – strangetimes Mar 10 '17 at 16:13
  • I have the same issue but its unknown crash I dont know how to resolved this issue any one please guide me .... – Ahmad Joyia Feb 26 '18 at 20:00
  • I have this crash and the explanation almost makes sense except for Fabric claims the same user has crashed 10 times, wouldn't this type of crash only happen once and be very rare and would probably never affect the same user again just because of what all has to align for it to happen? – casolorz Mar 08 '19 at 19:35
  • there is not a true fix for this, but I was able to workaround this by recreating the notification before I notified the NotificationManager (i know this isn't an option for everyone, but for me it is). that way when you set the icon, you're setting it with the current resource id. Looks like from the NotificationCompat.Builder docs that Google is planning to add a constructor to easily clone a Notification in the future so you won't have to fully reassemble a new Notification. – M. Smith Dec 01 '20 at 18:59
  • @M. Smith how you recreate the notification , what you mean by this in code ? – adel omar Nov 03 '21 at 07:42
57

Using VectorXml inside your notification has been known to cause this issue. Use png's

Bubunyo Nyavor
  • 2,511
  • 24
  • 36
  • 5
    Only PNGs were being used. – FishStix Oct 26 '16 at 17:45
  • 1
    In my case, I had vector in `drawable` folder and png's in `drawable-hdpi`, `xhdpi`, etc. But there was no png for `drawable-mdpi`, and it crashed on MDPI device on posting a notification. – Vadim Kotov Jan 24 '19 at 10:40
38

Don't use SVG on Kitkat!

I had the same issue every time when I wanted to show a notification on Kitkat. What caused the problem for me is that I have defined every icon in xml (from svg), the small icon and the action icon also. After I have replaced them with png-s the problem solved at my side.

bendaf
  • 2,981
  • 5
  • 27
  • 62
  • 8
    I can confirm. Vector drawables in notifications cause RemoteServiceException on KitKat. – Khizhny Andrey Mar 14 '18 at 14:00
  • 2
    In the case of KitKat, the problem was resolved when I replaced the XML with PNG in: new NotificationCompat.Builder(context, CHANNEL_ID).setSmallIcon(R.drawable.my_icon) – Andrew Glukhoff Jun 03 '18 at 18:46
  • 1
    This worked for me. I was running API 19 and used a SVG file for notification icon and was giving me this error, until I switched it to a small png icon – WHOATEMYNOODLES Aug 23 '19 at 21:00
12

My problem was that the icon I was using on

.setSmallIcon(R.drawable.ic_stat_push_notif)

wasn't generated accordingly. According to the official doc:

As described in Providing Density-Specific Icon Sets and Supporting Multiple Screens, you should create separate icons for all generalized screen densities, including low-, medium-, high-, and extra-high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed.

So the best way to fullfill the above, I used Notification Generator provided by Roman Nurik on https://romannurik.github.io/AndroidAssetStudio/index.html

In that way, you can use an image (taking into consideration that this has to have transparent background) and let the generator do the job for you generating the different sizes for notification icons.

The most important thing is that if the icon generator after you browse the image you are going to use shows you a white filled circle or square, there are problems with your image, maybe because it doesn't have any transparencies, so make sure that you has this ok.

Carlos Daniel
  • 2,459
  • 25
  • 30
  • 2
    In my case, I had vector in `drawable` folder and png's in `drawable-hdpi`, `xhdpi`, etc. But there was no png for `drawable-mdpi`, and it crashed on MDPI device on posting a notification. – Vadim Kotov Jan 24 '19 at 10:41
11

android.app.RemoteServiceException: Bad notification posted

I had the same issue, but I was resolved. My problem is ".xml file" of Remote view.

In my xml file I was added one View in between the LinearLayout for divider.

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:id="@+id/view"
    android:background="#000000" />

The above View component creating the Bad notification exception. This Exception reason is only xml file of Remoteviews.

After removing that View component, My code executed properly, without any exception. So I felt that Notification drawer not accepting any customized views.

So you don't draw any thing like the above view in the .xml file of RemoteView object.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Kona Suresh
  • 1,836
  • 1
  • 15
  • 25
8

In my app, this kind of bug happens only during upgrading. If the resource id changes in the newer version, Android RemoteView may fail to find the resource and throw out the RemoteServiceException. If you publish a 3rd version and do not change the resource id, the bugs may disappear only temporarily.

It is possible to reduce this kind of bugs by editing res/values/public.xml and res/values/ids.xml. Compiler will generate an individual resource id if the resource id is not in public.xml or ids.xml. When u change the resource name or add some new resources, the id may change and some devices may fail to find it.

So the step is as following:

  1. Decompile the apk file and in res/values find the public.xml and ids.xml
  2. Find all resources related to RemoteView in your app and copy them ( strings, dimen, drawable, layout, id, color... )
  3. Create public.xml and ids.xml under res/values in your source code and paste the lines u just copied

Note:

Gradle 1.3.0 and above ignore the local public.xml. To make it work, u need to add some script in your build.gradle

afterEvaluate {
    for (variant in android.applicationVariants) {
        def scope = variant.getVariantData().getScope()
        String mergeTaskName = scope.getMergeResourcesTask().name
        def mergeTask = tasks.getByName(mergeTaskName)
        mergeTask.doLast {
            copy {
                int i=0
                from(android.sourceSets.main.res.srcDirs) {
                    include 'values/public.xml'
                    rename 'public.xml', (i == 0? "public.xml": "public_${i}.xml")
                    i++
                }
                into(mergeTask.outputDir)
            }
        }
    }
}

Note: This script does not support submodules project. I am trying to fix it.

thundertrick
  • 1,634
  • 1
  • 17
  • 22
6

In Android Studio version 3.0.0 and above, when adding a new image in the drawables folder choose drawable instead of drawable-v24.enter image description here

If the image,you are using, is alread a (v24) just copy it and paste it in its same directory (eg. drawables). This time it will ask you which regular or v24 - just make sure its not the v24 and try it again this should fix the error.

Haider Malik
  • 1,581
  • 1
  • 20
  • 23
  • 1
    Notice - if you are in "Android" view, switch it to "Project" view. In Android view, you may not see the drawables v24 directory – Richard Miller Nov 06 '19 at 10:17
  • I think this works fine for me. You can put that vector xml file in both drawable and drawable v24. Those android version less than or equal to Marsha mellow will pick it up from drawable folder, and the newer version will pick it up from drawable v24. – Yosidroid Jan 31 '21 at 16:07
  • Yes it happened in my case, my mipmap was only for v26 – ashishdhiman2007 Feb 08 '22 at 13:03
6

Just in case the icon is not important, you can replace,

R.drawable.your_icon

To

android.R.drawable.some_standard_icon

This works!

Ashwin Balani
  • 745
  • 7
  • 19
4

I had RemoteServiceException when use Notification in my class extends from FirebaseMessagingService. I added the following code to AndroidManifest.xml:

<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_small" />

Also resource ic_small set in instance of a class Notification.Builder by method setSmallIcon(int icon).

4

If you have a notification visible while your app is updated, you might run into this. What you may need to do is create a BroadcastReceiver that waits for a PACKAGE_CHANGED message, at which point you shutdown all your services which will also dismiss their associated notifications.

 <receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_CHANGED" />
    </intent-filter>
</receiver>
Glaucus
  • 848
  • 8
  • 14
3

You have pass same icon

     <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_name" />

and you notification

 NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_stat_name)
                        .setContentTitle("Title")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
Tarun Umath
  • 900
  • 10
  • 7
  • 2
    I've passed vector image as a resource and I think it caused the crashes on oneplus/android 6 devices. Not sure for 100%. – Alexey Sep 09 '18 at 05:21
2

Same issue happened with me as well and I have solved the same

REASON: This is happening because of we are using vector drawable for RemoteViews and vector drawable generates drawable at compile-time. Also I am not sure why some devices are not able to detect the generated drawable resources id while we are upping the app. But yes this was the reason.

REPRODUCE Steps 1. Install previous build. 2. Send a notification 3. Update the build with next version code 4. After updating the app don't open the app and send notification again

SOLUTION Replace the vector drawable with normal drawable(.png or .jpg) file.

I hope this resolves the problem.

Gajju
  • 31
  • 1
  • 5
1

You can put that vector xml file in both drawable and drawable v24. Those android version less than or equal to Android 6 will pick it up from drawable folder, and and newer version above android 6 will pick it up from drawable v24.

Yosidroid
  • 2,053
  • 16
  • 15
1

Its not about the Image type (vector, png, etc.) but the folder to which you are referring to.

For me the error caused was due to a device (Nougat) referring to an icon present in v26 folder.

Solution: Just add the relevant icon to the other folder as well and the issue will be gone.

Prajwal Waingankar
  • 2,534
  • 2
  • 13
  • 20
0

I had the same issue when I set a notification in a bundle. I tried this and it solved my problem:

builder.setLargeIcon(large_icon);
builder.setSmallIcon(R.drawable.small_icon);

Make sure that setLargeIcon() invoked before setSmallIcon().

Jelly
  • 1
  • 1
0

I too had the same issue. The issue is with the icon which you are using, I was using android.R.drawable.stat_sys_download. Go to drawables.xml and paste this.

<resources>
 <item name="ic_start_download" type="drawable">@android:drawable/stat_sys_download</item>
</resource>

and then in your code

builder.setSmallIcon(R.drawable.ic_start_download);

You can try some other image instead of this image

0

My way to solve this: I had "bad" views in my layout (ex: a checkbox) - so I removed them.

RemoteViews seem to support only images and texts (to be confirmed by reading the doc).

Benjamin Piette
  • 3,645
  • 1
  • 27
  • 24
0

I had RemoteServiceException when use android.support.constraint.ConstraintLayout. Change it to LinearLayout or Relative and also android:layout_height="wrap_content" for container

0

(this is not solution for current question but helps someone with similar core issue) I too had the same issue, But in my case I have used corrupted .png file which is causing same issue. So I have deleted it and re-included correct .png file.

0

Please replace <android.support.v7.widget.AppCompatTextView with <TextView from custom notification layout.

Because android.support.v7.widget.AppCompatTextView or android.support.v7.widget.AppCompatImageView only works at runtime.

So Use TextView or ImageView

Ahamadullah Saikat
  • 4,437
  • 42
  • 39
0

If any one still facing this issue : Add a png file in your drawable folder with name ic_stat_ic_notification (or any name u like )

and in your manifest add below couple of lines

and u can create your icons over here - > https://romannurik.github.io/AndroidAssetStudio/icon

Jayapen Jose
  • 55
  • 1
  • 7
0

I got this error due to autolink and linksClickable options in textview in notification view:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="all"
        android:linksClickable="true"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/white" />

Be careful!

Master
  • 690
  • 6
  • 18
0

It was a problem of icon location. In my case the notification icon was in drawable-anydpi-v24, I simply copied the icon in drawable folder and the error has gone.

protanvir993
  • 2,759
  • 1
  • 20
  • 17
0

Got this error in my Flutter android app and checked to see that all the resources are present and named correctly but still not working, I was using resources from mipmap. I changed it to drawable and placed the notification icons inside drawble folders and fixed the issue, hoping it might help someone later on

-1

Synchrinize the project and than Clean it, File > Synchronize then : Build > Clean Project

I hope that will help you all, It's work for me

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
-3

This worked for me. Comment the reference of the icon and thus be able to use the NotificationCompat.Builder without problems.

    $msg_notificacion = [
                        'title'         => "titulonotif",
                       // "icon" : "myicon",
                        'body'          =>"cuerponotif"
                    ];