Android 桌面图标右上角显示未读消息数字

背景:

       在Android原生系统中,众所周知不支持桌面图标显示未读消息提醒的数字,虽然第三方控件BadgeView可以实现应用内的数字提醒。但对于系统的图标,特别是app的logo图标很难实现数字标志,即使是绘图的方式不断修改,但这种方式天生弊端,实用性很差。但幸运的是,一些强大的手机厂商(小米,三星,索尼)提供了私有的API,但也带来了难度,API的不同就意味着代码量的增加和兼容性问题更加突出。

      现在我们来看看他们是如何实现的:首先看张图片


实现原理:

        首先我们要明白 并不是应用本身处理对启动图标进行修改、图标的动态修改的过程主要是在Launcher里面完成的.在应用安装,更新,卸载的时候,都会有广播发出,Launcher在LauncherApplication 中注册广播,在LauncherModel中处理接收到广播的消息,重新加载更新应用信息(如:应用图标、文字等)。但是原生的android系统是并不支持该特性的(及不能通过发送特定的系统广播 达到动态修改启动图标的效果),但是在强大的第三方Android手机厂商(如:三星、小米)的系统源码深度定制下、通过修改了Launcher源代码,增加/注册了新的广播接收器用来接收应用发送来的未读消息数广播,接收到广播后,系统将未读消息的数目显示事件交给Launcher去处理,调用相关方法去重绘应用的icon,最终达到动态更新应用图标的效果。

示例代码:

public class LauncherBadgeHelper {

    /**
     * Set badge count
* 针对 Samsung / xiaomi / sony 手机有效 * * @param context The context of the application package. * @param count Badge count to be set */ public static void setBadgeCount(Context context, int count) { if (count <= 0) { count = 0; } else { count = Math.max(0, Math.min(count, 99)); } if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")) { sendToXiaoMi(context, count); } else if (Build.MANUFACTURER.equalsIgnoreCase("sony")) { sendToSony(context, count); } else if (Build.MANUFACTURER.toLowerCase().contains("samsung")) { sendToSamsumg(context, count); } else { sendToSamsumg(context, count); } } /** * 向小米手机发送未读消息数广播 * * @param count */ private static void sendToXiaoMi(Context context, int count) { try { Class miuiNotificationClass = Class.forName("android.app.MiuiNotification"); Object miuiNotification = miuiNotificationClass.newInstance(); Field field = miuiNotification.getClass().getDeclaredField("messageCount"); field.setAccessible(true); field.set(miuiNotification, String.valueOf(count == 0 ? "" : count)); // 设置信息数-->这种发送必须是miui 6才行 } catch (Exception e) { LogController.e(e.toString()); // miui 6之前的版本 Intent localIntent = new Intent( "android.intent.action.APPLICATION_MESSAGE_UPDATE"); localIntent.putExtra( "android.intent.extra.update_application_component_name", context.getPackageName() + "/" + getLauncherClassName(context)); localIntent.putExtra( "android.intent.extra.update_application_message_text", String.valueOf(count == 0 ? "" : count)); context.sendBroadcast(localIntent); } } /** * 向索尼手机发送未读消息数广播
* 据说:需添加权限: [未验证] * * @param count */ private static void sendToSony(Context context, int count) { String launcherClassName = getLauncherClassName(context); if (launcherClassName == null) { return; } boolean isShow = true; if (count == 0) { isShow = false; } Intent localIntent = new Intent(); localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE"); localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", isShow);//是否显示 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);//启动页 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));//数字 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());//包名 context.sendBroadcast(localIntent); } /** * 向三星手机发送未读消息数广播 * * @param count */ private static void sendToSamsumg(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); } /** * 重置、清除Badge未读显示数
* * @param context */ public static void resetBadgeCount(Context context) { setBadgeCount(context, 0); } /** * Retrieve launcher activity name of the application from the context * * @param context The context of the application package. * @return launcher activity name of this application. From the * "android:name" attribute. */ private static String getLauncherClassName(Context context) { PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); // To limit the components this Intent will resolve to, by setting an // explicit package name. intent.setPackage(context.getPackageName()); intent.addCategory(Intent.CATEGORY_LAUNCHER); // All Application must have 1 Activity at least. // Launcher activity must be found! ResolveInfo info = packageManager .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); // get a ResolveInfo containing ACTION_MAIN, CATEGORY_LAUNCHER // if there is no Activity which has filtered by CATEGORY_DEFAULT if (info == null) { info = packageManager.resolveActivity(intent, 0); } return info.activityInfo.name; } }

可以看出小米,三星,索尼处理方式都是通过发送广播来实现的。

但是:小米MIUI6以后,改变了处理方式,弃用了发送广播的方式,改为通过发送通知。

一、基本介绍

1、默认的情况

当app 向通知栏发送了一条通知 (通知不带进度条并且用户可以删除的),那么桌面app icon角标就会显示1.此时app显示的角标数是和通知栏里app发送的通知数对应的,即向通知栏发送了多少通知就会显示多少角标

二、实现代码

第三方app需要用反射来调用,参考代码:

NotificationManager mNotificationManager = (NotificationManager) this

.getSystemService(Context.NOTIFICATION_SERVICE);

Notification.Builder builder = new Notification.Builder(this)

.setContentTitle(“title”).setContentText(“text”).setSmallIcon(R.drawable.icon);

Notification notification = builder.build();

try {

Field field = notification.getClass().getDeclaredField(“extraNotification”);

Object extraNotification = field.get(notification);

Method method = extraNotification.getClass().getDeclaredMethod(“setMessageCount”, int.class);

method.invoke(extraNotification, mCount);

} catch (Exception e) {

e.printStackTrace();

}

mNotificationManager.notify(0,notification);

自己在之前的代码根据官方代码总结新的方法如下:

  /**
     * 向小米手机发送未读消息数广播miui6以后
     *
     * @param count
     */
    private static void sendToXiaoMi2(Context context, int count) {
        NotificationManager mNotificationManager = (NotificationManager) MyApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(MyApplication.getContext()).setContentTitle("title").setContentText("text").setSmallIcon(R.drawable.ico_haoyilogo);
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            notification = builder.build();
        }
        try {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, count);
            mNotificationManager.notify(10, notification);
        } catch (Exception e) {
            e.printStackTrace();
            LogController.e(e.toString());
            // miui 6之前的版本
            Intent localIntent = new Intent(
                    "android.intent.action.APPLICATION_MESSAGE_UPDATE");
            localIntent.putExtra(
                    "android.intent.extra.update_application_component_name",
                    context.getPackageName() + "/" + getLauncherClassName(context));
            localIntent.putExtra(
                    "android.intent.extra.update_application_message_text", String.valueOf(count == 0 ? "" : count));
            context.sendBroadcast(localIntent);
        }
    }
这样既能兼容MIUI6之前的,还能实现MIUI6以后的。自己在开发的时候经过测试,发现MIUI内部对于相同的消息数字是不显示的,由于我测试的时候用的是写死的数字,导致走了很多弯路。还有,自己在查找资料的时候发现有许多朋友都遇到过这样的问题,未读消息数字只有在第一次安装的时候才显示,进入后再设置就没有了,我估计都是因为数字相同造成的。

细想一下,MIUI这种做法也挺好的,消息数字和通知绑定,当来通知时触发事件,从而桌面图标数字动态改变。当我们清楚通知时,清空数字。自己也调研了iOS的做法,他们只是通过调用系统的一个方法将消息数字传进去即可,做法类似于Android 通过发送广播方式,和三星一样。

那么,小米是如何做到累加的呢。

我们只需定义全局变量count,初始值设置为1,然后发送通知后,手动改变count值,count=count+1。

友情链接:

https://github.com/lixiangers/BadgeUtil





你可能感兴趣的:(Android 桌面图标右上角显示未读消息数字)