[android] How to display count of notifications in app launcher icon

samsung galaxy note 2 android version 4.1.2

I know that this question was asked before and the reply was not possible

How to display balloon counter over application launcher icon on android

Nevertheless yesterday I updated the facebook app and it started to show a counter of unread messages private messages. How come facebook app can and I cant do so for my app?

facebook icon

enter image description here

samsung galaxy note 2 android version 4.1.2

This question is related to android android-layout notifications icons

The answer is


I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.


ShortcutBadger is a library that adds an abstraction layer over the device brand and current launcher and offers a great result. Works with LG, Sony, Samsung, HTC and other custom Launchers.

It even has a way to display Badge Count in Pure Android devices desktop.

Updating the Badge Count in the application icon is as easy as calling:

int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);

It includes a demo application that allows you to test its behavior.


It works in samsung touchwiz launcher

public static void setBadge(Context context, int count) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
        return;
    }
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", context.getPackageName());
    intent.putExtra("badge_count_class_name", launcherClassName);
    context.sendBroadcast(intent);
}

public static String getLauncherClassName(Context context) {

    PackageManager pm = context.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resolveInfos) {
        String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
        if (pkgName.equalsIgnoreCase(context.getPackageName())) {
            String className = resolveInfo.activityInfo.name;
            return className;
        }
    }
    return null;
}

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            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);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to notifications

NotificationCompat.Builder deprecated in Android O No notification sound when sending notification from firebase in android Android Push Notifications: Icon not displaying in notification, white square shown instead How to display multiple notifications in android Actionbar notification count icon (badge) like Google has How to display count of notifications in app launcher icon Android notification is not showing How to create a notification with NotificationCompat.Builder? Open application after clicking on Notification How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Examples related to icons

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp? Round button with text and icon in flutter Add tooltip to font awesome icon How to add icons to React Native app How to set app icon for Electron / Atom Shell App Android Push Notifications: Icon not displaying in notification, white square shown instead Pyinstaller setting icons don't change How to change Toolbar home icon color iOS how to set app icon and launch images Put search icon near textbox using bootstrap