Android adds a badge to the application (Badge)

1. Introduction to requirements What does

the corner mark mean?

Look at the picture below to understand:


you can see the red circle in the upper right corner of the Tesco app in the picture, with the number 10 in it, which is a kind of corner mark.

Angle mark, English is badge, which means "badge, badge, medal; symbol, mark".

Generally speaking, the corner marker of the application is used to mark how many notifications (Notification) are unread (unread). Once the notification is clicked into the application to read, the corner marker will disappear.

2. The origin of Android corner labels The

corner labels were originally something in Apple's iOS. Android does not support corner labels natively, because Google means that everyone can use Notification (prompt bar), and corner labels are really great for Virgo" The risk of jumping off a cliff. Fortunately I'm not...

In a recent company's project, a new customer request is to add a corner label function to our encrypted messaging application, because our partner is Samsung (see my article: Programmers are in France | I was targeted by the French Ministry of Defense!), so I went online to find relevant information.

When I was looking for it, I realized that the Android native does not support corner labels mentioned above. But it doesn't matter, powerful third-party Android manufacturers can add corner labels by operating in the custom Launcher (launcher).

Of course, I was looking for how to add corner labels to Samsung's mobile devices for the first time, but I was fortunate enough to find a more general project on Github.

It was Stack Overflow that led me to Github, and it was Google that led me to Stack Overflow, so I would say: Why do programmers have to use Google and Stack Overflow? .

3. Nice Github project

Generally speaking, the most cited Github project for adding and removing corner labels in Android is written by this Chinese: https://github.com/leolin310148/ShortcutBadger

This project is quite good, although the update is not particularly diligent, but the latest time The update was on October 31, 2016, which is two months ago, and is still acceptable.

Xu Yisheng, the author of "The Legend of Android Heroes" and "The Legend of Android Heroes: Magic Weapons", also built a project on his Github: https://github.com/xuyisheng/ShortcutHelper , which is very interesting, and there is also a project called "" "Crazy mode" adds the function of adding 99 superscript numbers to all applications on the mobile phone desktop. Of course, there are also codes to be removed, otherwise Virgo will be dizzy~

The principle of adding superscripts is to send a Broadcast (broadcast) , specify the packageName (package name), className (class name), count (number of angular labels) of the application that needs to be added in the broadcast Intent. Of course, the action of the Intent for the corner mark operation of the mobile phone of different manufacturers is different.

Therefore, if we want to add a corner label to the application in our mobile phone, we only need to simply use the codes in the above two projects, and generally do not need to move all the projects. Of course, if you want to adapt to all mobile phones, you can reference the project in its entirety.

For example, if I want to add a logo to a Samsung mobile phone application, then I only need to do the following steps:

Add the permissions to read and write the logo in AndroidManifest.xml:
<uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />

Write a class yourself, name it whatever you want, such as BadgeUtils, and add the following to the class:
public class BadgeUtils {
  private static final String INTENT_ACTION = "android.intent.action.BADGE_COUNT_UPDATE";
  private static final String INTENT_EXTRA_BADGE_COUNT = "badge_count";
  private static final String INTENT_EXTRA_PACKAGENAME = "badge_count_package_name";
  private static final String INTENT_EXTRA_ACTIVITY_NAME = "badge_count_class_name";

  public static void setBadgeCount(Context context, ComponentName componentName, int badgeCount) {
    Intent intent = new Intent(INTENT_ACTION);     
    intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount);    
    intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName());    
    intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName());
    context.sendBroadcast (intent);  
  }
}

When using the above code, you only need to pass in three parameters, namely:

Context : The Context of the application. Simple.
ComponentName : The component name, which is a little troublesome. It can be obtained like this (applicationContext is the Context of the application):
applicationContext.getPackageManager()
.getLaunchIntentForPackage(applicationContext.getPackageName())
.getComponent()

badgeCount : The number of badges, such as 10. Simple.
Of course, if you don't want the trouble of passing in three parameters, you can also write another method getLauncherClassName, you only need to pass in two parameters. The code in BadgeUtils becomes:
public class BadgeUtils {
  private static final String INTENT_ACTION = "android.intent.action.BADGE_COUNT_UPDATE";
  private static final String INTENT_EXTRA_BADGE_COUNT = "badge_count";
  private static final String INTENT_EXTRA_PACKAGENAME = "badge_count_package_name";
  private static final String INTENT_EXTRA_ACTIVITY_NAME = "badge_count_class_name";

  public static void setBadgeCount(Context context, int badgeCount) {
    String launcherClassName = getLauncherClassName(context);
    if (launcherClassName == null) {
      return;
    }

    Intent intent = new Intent(INTENT_ACTION);     
    intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount);    
    intent.putExtra(INTENT_EXTRA_PACKAGENAME, context.getPackageName());    
    intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, launcherClassName);

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

When using it, you can pass in two parameters:

Context : The Context of the application.
badgeCount : The number of badges, such as 10.
4. Clear the badge

To clear the badge of the application is very simple, just pass 0 to the badgeCount.

BadgeUtils.setBadgeCount(context,       
context.getPackageManager()               
.getLaunchIntentForPackage(context.getPackageName())                
.getComponent(),        
0);

or

BadgeUtils.setBadgeCount(context, 0);

5. Correcting minor problems The

above https://github.com/leolin310148/ShortcutBadger project basically includes the code implementation of most Android manufacturers who can customize the corner label to add corner labels, but it also mentions:

Samsung There are many similarities with the code of LG (these two brothers and sisters), even the action in the broadcast Intent processed by the corner mark is the same, both:

"android.intent.action.BADGE_COUNT_UPDATE"

But the author wrote comments in the two corner operation implementation classes of Samsung and LG:

// Deprecated, Samsung devices will use DefaultBadger

// Deprecated, LG devices will use DefaultBadger

It means "Samsung and LG's implementation code has been Deprecated (invalid), please use the DefaultBadger class".

Therefore, these two need to be implemented using https://github.com/leolin310148/ShortcutBadger/blob/master/ShortcutBadger/src/main/java/me/leolin/shortcutbadger/impl/DefaultBadger.java :
private static final String INTENT_ACTION = "android.intent.action.BADGE_COUNT_UPDATE";
private static final String INTENT_EXTRA_BADGE_COUNT = "badge_count";
private static final String INTENT_EXTRA_PACKAGENAME = "badge_count_package_name";
private static final String INTENT_EXTRA_ACTIVITY_NAME = "badge_count_class_name";

@Override
public void executeBadge(Context context, ComponentName componentName, int badgeCount) throws ShortcutBadgeException {
  Intent intent = new Intent(INTENT_ACTION);
  intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount);
  intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName());
  intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName());

  if (BroadcastHelper.canResolveBroadcast(context, intent)) {
    context.sendBroadcast (intent);
  } else {
    throw new ShortcutBadgeException("unable to resolve intent: " + intent.toString());
  }
}


However, there is a small problem with the above code, which is the sentence

if (BroadcastHelper.canResolveBroadcast(context, intent)) {

On some devices (such as Samsung Galaxy S5), an Exception will be thrown, and the BroadcastReceiver that handles the "android.intent.action.BADGE_COUNT_UPDATE" Intent cannot be found, which is very strange.

But on some devices (like Samsung Galaxy A5) it works fine again without throwing exception.

The solution is to remove this detection and put

if (BroadcastHelper.canResolveBroadcast(context, intent)) {
  context.sendBroadcast (intent);
} else {
  throw new ShortcutBadgeException("unable to resolve intent: " + intent.toString());
}

replace with simple

context.sendBroadcast (intent);

That's it.

That is the code I implemented above.

6. Summarize

the addition and removal of Android corner labels. After all, it is based on the customization of the Launcher of major mobile phone manufacturers, so it is not an orthodox Android skill. With the change of the manufacturer's Launcher, your code may not necessarily be useful in the future, so It needs to be constantly revised and "innovative".

But as the so-called "life is tossing", and this is why we like the Android system. This cute robot can withstand our random tossing, and its application in the embedded field is also very promising.

When you usually learn programming, you can also summarize your own code or experience into the Github project, to benefit yourself and others, and to improve your industry reputation. Introduction to Git, Github

and Gitlab and Basic Use of
Github | How to Contribute to Android Open Source Projects and Submit Patches

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326359452&siteId=291194637