应用图标右上角消息数量的显示

来源:互联网 发布:原车轮毂数据查询 编辑:程序博客网 时间:2024/05/18 01:40
// 让app logo显示消息数量
public void showCount() {
NotificationManager mNotificationManager = (NotificationManager) this


.getSystemService(Context.NOTIFICATION_SERVICE);


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


// .setContentTitle("title").setContentText("text").setSmallIcon(R.drawable.point_on).setAutoCancel(true);;


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, allCount);


} catch (Exception e) {


e.printStackTrace();


}
mNotificationManager.notify(0, notification);
BadgeUtil.setBadgeCount(notification, context, allCount);


}












/*
 * 应用启动图标未读消息数显示 工具类  (效果如:QQ、微信、未读短信 等应用图标)<br/>

*  这里包含了小米,sony,Samsung,htc,nova,huawei,zuk  全部亲测有效
 * */
public class BadgeUtil {
 /**
     * Set badge count<br/>
     * 针对 Samsung / xiaomi / sony 手机有效
     * @param context The context of the application package.
     * @param count Badge count to be set
     */
    public static void setBadgeCount(Notification notification,Context context, int count) {
        if (count <= 0) {
            count = 0;
        } else {
            count = Math.max(0, Math.min(count, 99));
        }


        if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")) {
            sendToXiaoMi(notification, context, count);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("sony")) {
            sendToSony(context, count);
        } else if (Build.MANUFACTURER.toLowerCase().contains("samsung")) {
            sendToSamsumg(context, count);
        } else if (Build.MANUFACTURER.toLowerCase().contains("htc")) {
            sendToHTC(context, count);
        }  else if (Build.MANUFACTURER.toLowerCase().contains("nova")) {
            sendToNova(context, count);
        }else if (Build.MANUFACTURER.toLowerCase().contains("huawei")) {
        String versionString = android.os.Build.VERSION.RELEASE;
        int version=Integer.parseInt(versionString.substring(0, 1));
        if(version>=5){
        sendToHuaWei(context, count);
        }
   
        }else if (Build.MANUFACTURER.toLowerCase().contains("zuk")) {
        sendToZUK(context, count);
        } 
        else {
//            Toast.makeText(context, "Not Support", Toast.LENGTH_LONG).show();
        }
    }




    /**
     * 向小米手机发送未读消息数广播
     * @param count
     */
    private static void sendToXiaoMi(Notification notification,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才行


//            Field field = notification.getClass().getDeclaredField("extraNotification");
//
//            Object extraNotification = field.get(notification);
//
//            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
//
//            method.invoke(extraNotification, count);


        } catch (Exception e) {
            e.printStackTrace();
            // 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);
        }
    }




    /**
     * 向索尼手机发送未读消息数广播<br/>
     * 据说:需添加权限:<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" /> [未验证]
     * @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);
    }
//华为手机
    private static void sendToHuaWei(Context context, int count){
    Bundle localBundle = new Bundle();
        localBundle.putString("package", context.getPackageName());
        localBundle.putString("class", getLauncherClassName(context));
        localBundle.putInt("badgenumber", count);
        context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle);
    }


    /**
     * 向三星手机发送未读消息数广播
     * @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);
    }
    //HTC Badge
    private static void sendToHTC(Context context, int count){
    Intent intentNotification = new Intent("com.htc.launcher.action.SET_NOTIFICATION");
    ComponentName localComponentName = new ComponentName(context.getPackageName(),
    getLauncherClassName(context));
    intentNotification.putExtra("com.htc.launcher.extra.COMPONENT", localComponentName.flattenToShortString());
    intentNotification.putExtra("com.htc.launcher.extra.COUNT", count);
    context.sendBroadcast(intentNotification);


    Intent intentShortcut = new Intent("com.htc.launcher.action.UPDATE_SHORTCUT");
    intentShortcut.putExtra("packagename", context.getPackageName());
    intentShortcut.putExtra("count", count);
    context.sendBroadcast(intentShortcut);
    }
    //Nova Badge
    private static void sendToNova(Context context, int count){
    ContentValues contentValues = new ContentValues();
    contentValues.put("tag", context.getPackageName() + "/" +
           getLauncherClassName(context));
    contentValues.put("count", count);
    context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"),
           contentValues);
    }
    //ZUK
    private static void sendToZUK(Context context, int counts){       
    Bundle extra = new Bundle();
    ArrayList<String> ids = new ArrayList<String>();
    // 以列表形式传递快捷方式id,可以添加多个快捷方式id
    ids.add("custom_id_1");
    ids.add("custom_id_2");
    extra.putStringArrayList("app_shortcut_custom_id", ids);
    extra.putInt("app_badge_count", counts);
    Bundle b = null;
    b = context.getContentResolver().call(Uri.parse("content://" + "com.android.badge" + "/" + "badge"),"setAppBadgeCount", null, extra);
    boolean result = false;
    if (b != null) {
    result = true;
    }else {
    result = false;  
    }  
    return;
   
    /**
     * 重置、清除Badge未读显示数<br/>
     * @param context
     */
    public static void resetBadgeCount(Notification notification,Context context) {
        setBadgeCount(notification, 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;
    }
   
}

阅读全文
0 0