Android 桌面角標(biāo)在各大品牌機(jī)型上的實(shí)現(xiàn)

原文:https://blog.csdn.net/uyy203/article/details/70160752

由于角標(biāo)在Android原生的系統(tǒng)中沒(méi)有支持罗捎,所以各個(gè)Android手機(jī)廠商各自為政现横。

正如很多資料所說(shuō),這一功能完全是效仿IOS耻蛇,Android本不存在的,對(duì)于不支持的廠商如魅族搀暑、中興蚂四、酷派光戈,必須為他們不盲目跟風(fēng)而點(diǎn)贊。

做起適配來(lái)遂赠,真的很麻煩久妆,要針對(duì)各個(gè)廠商逐個(gè)去寫(xiě)以及測(cè)試。

目前做到支持小米解愤、華為镇饺、三星乎莉、LG送讲、VIVO、ZUK惋啃、HTC哼鬓、NOVA等廠商的Andorid系統(tǒng)

效果如下圖所示


image.png

特別說(shuō)明一下小米自MIUI6.0以后,角標(biāo)的顯示和通知欄Notification綁在一起边灭。目前我發(fā)現(xiàn)的做法异希,就只有小米需要和Notification綁在一起才能生效。

不過(guò)我在這里的例子因產(chǎn)品需求绒瘦,全部機(jī)型的做法都把Notification綁上称簿。

消息通知ID

private int MQTT_IM_NOTIFICATION_ID=1007;

通知欄Notification的定義

String content = 2 + "個(gè)聯(lián)系人發(fā)了" + i + "條消息";
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        builder.setSmallIcon(R.drawable.chat_notify_icon);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setTicker("收到" + i + "條消息");
        builder.setWhen(System.currentTimeMillis());
        Intent intent = new Intent(getBaseContext(), MainActivity.class);
 
        intent.setAction(getApplicationContext().getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);
        builder.setContentTitle(getResources().getText(R.string.app_name));
        builder.setContentText(content);
 
        final Notification n = builder.build();
        int defaults = Notification.DEFAULT_LIGHTS;
 
        defaults |= Notification.DEFAULT_SOUND;
 
        defaults |= Notification.DEFAULT_VIBRATE;
 
 
        n.defaults = defaults;
        n.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;

廠商

String content = 2 + "個(gè)聯(lián)系人發(fā)了" + i + "條消息";
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        builder.setSmallIcon(R.drawable.chat_notify_icon);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setTicker("收到" + i + "條消息");
        builder.setWhen(System.currentTimeMillis());
        Intent intent = new Intent(getBaseContext(), MainActivity.class);
 
        intent.setAction(getApplicationContext().getPackageName());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);
        builder.setContentTitle(getResources().getText(R.string.app_name));
        builder.setContentText(content);
 
        final Notification n = builder.build();
        int defaults = Notification.DEFAULT_LIGHTS;
 
        defaults |= Notification.DEFAULT_SOUND;
 
        defaults |= Notification.DEFAULT_VIBRATE;
 
 
        n.defaults = defaults;
        n.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;

廠商獲取

 OSName=android.os.Build.BRAND.trim().toUpperCase();

廣播
特別注意,小米的通知欄提示需要延時(shí)操作才會(huì)出現(xiàn)角標(biāo)惰帽,但是偶爾還是沒(méi)法出現(xiàn)憨降,暫時(shí)沒(méi)有特別好的解決辦法,不過(guò)目前能保證做到較高的成功率该酗。

除了小米以外授药,其他實(shí)現(xiàn)基本沒(méi)什么問(wèn)題士嚎。

    //小米
    private static void setBadgeOfXiaomi(final Context context,final Notification notification,final int NOTIFI_ID,final int  num){
 
 
        new Handler().postDelayed(new Runnable() {
 
            @Override
            public void run() {
 
 
                try {
 
                    Field field = notification.getClass().getDeclaredField("extraNotification");
 
                    Object extraNotification = field.get(notification);
 
                    Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
 
                    method.invoke(extraNotification, num);
 
                } catch (Exception e) {
 
                    e.printStackTrace();
                    Log.e("Xiaomi" + " Badge error", "set Badge failed");
 
                }
 
//                mNotificationManager.notify(0,notification);
                NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
                if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
            }
        },550);
 
    }

三星 & LG


   //三星和LG
    private static void setBadgeOfSamsung(Context context,Notification notification, int NOTIFI_ID,int num) {
        // 獲取你當(dāng)前的應(yīng)用
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
 
        try {
            Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
            intent.putExtra("badge_count", num);
            intent.putExtra("badge_count_package_name", context.getPackageName());
            intent.putExtra("badge_count_class_name", launcherClassName);
            context.sendBroadcast(intent);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("SAMSUNG" + " Badge error", "set Badge failed");
        }
    }

華為

華為及其榮耀系列通用,不需要官網(wǎng)認(rèn)證

   //華為 系列
    private static void setBadgeOfHuaWei(Context context, Notification notification,int NOTIFI_ID,int num) {
 
 
        try{
            Bundle localBundle = new Bundle();
            localBundle.putString("package", context.getPackageName());
            localBundle.putString("class", getLauncherClassName(context));
            localBundle.putInt("badgenumber", num);
            context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
        }catch(Exception e){
            e.printStackTrace();
            Log.e("HUAWEI" + " Badge error", "set Badge failed");
        }
 
}

索尼

   //索尼
    private static void setBadgeOfSony(Context context,Notification notification,int NOTIFI_ID, int num){
        String numString="";
        String activityName = getLauncherClassName(context);
        if (activityName == null){
            return;
        }
        Intent localIntent = new Intent();
//        int numInt = Integer.valueOf(num);
        boolean isShow = true;
        if (num < 1){
            numString = "";
            isShow = false;
        }else if (num > 99){
            numString = "99";
        }
 
        try {
            localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", isShow);
            localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
            localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", activityName);
            localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", numString);
            localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());
            context.sendBroadcast(localIntent);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("SONY" + " Badge error", "set Badge failed");
        }
    }

VIVO

 //VIVO
    private static void setBadgeOfVIVO(Context context,Notification notification,int NOTIFI_ID,int num){
        try {
            Intent localIntent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
            localIntent.putExtra("packageName", context.getPackageName());
            localIntent.putExtra("className", getLauncherClassName(context));
            localIntent.putExtra("notificationNum", num);
            context.sendBroadcast(localIntent);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("VIVO" + " Badge error", "set Badge failed");
        }
    }

OPPO

目前只支持部分機(jī)型


   //OPPO *只支持部分機(jī)型
    private static void setBadgeOfOPPO(Context context, Notification notification,int NOTIFI_ID,int num){
        try {
 
            if (num == 0) {
                num = -1;
            }
 
            Intent intent = new Intent("com.oppo.unsettledevent");
            intent.putExtra("pakeageName", context.getPackageName());
            intent.putExtra("number", num);
            intent.putExtra("upgradeNumber", num);
            if (canResolveBroadcast(context, intent)) {
                context.sendBroadcast(intent);
            } else {
 
                    try {
                        Bundle extras = new Bundle();
                        extras.putInt("app_badge_count", num);
                        context.getContentResolver().call(Uri.parse("content://com.android.badge/badge"), "setAppBadgeCount", null, extras);
 
                        NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
                        if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
                    } catch (Throwable th) {
                        Log.e("OPPO" + " Badge error", "unable to resolve intent: " + intent.toString());
                    }
            }
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("OPPO" + " Badge error", "set Badge failed");
        }
    }

ZUK

  //ZUK
    private static void setBadgeOfZUK(Context context,Notification notification,int NOTIFI_ID, int num){
         final Uri CONTENT_URI = Uri.parse("content://com.android.badge/badge");
        try {
            Bundle extra = new Bundle();
            extra.putInt("app_badge_count", num);
            context.getContentResolver().call(CONTENT_URI, "setAppBadgeCount", null, extra);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("ZUK" + " Badge error", "set Badge failed");
        }
 
    }

HTC


    //HTC
    private static void setBadgeOfHTC(Context context,Notification notification,int NOTIFI_ID,int num){
 
        try {
            Intent intent1 = new Intent("com.htc.launcher.action.SET_NOTIFICATION");
            intent1.putExtra("com.htc.launcher.extra.COMPONENT", context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().flattenToShortString());
            intent1.putExtra("com.htc.launcher.extra.COUNT", num);
 
            Intent intent = new Intent("com.htc.launcher.action.UPDATE_SHORTCUT");
            intent.putExtra("packagename", context.getPackageName());
            intent.putExtra("count", num);
 
            if (canResolveBroadcast(context, intent1) || canResolveBroadcast(context, intent)) {
                context.sendBroadcast(intent1);
                context.sendBroadcast(intent);
            } else {
                Log.e("HTC" + " Badge error", "unable to resolve intent: " + intent.toString());
            }
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("HTC" + " Badge error", "set Badge failed");
        }
 
    }

NOVA

    //NOVA
    private static void setBadgeOfNOVA(Context context,Notification notification,int NOTIFI_ID,int num){
        try{
            ContentValues contentValues = new ContentValues();
            contentValues.put("tag", context.getPackageName()+ "/" +getLauncherClassName(context));
            contentValues.put("count", num);
            context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), contentValues);
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
            Log.e("NOVA" + " Badge error", "set Badge failed");
        }
    }

其他

做個(gè)備案吧悔叽,這個(gè)真不一定能生效莱衩,只能從大多數(shù)的做法里摸規(guī)律

    //其他
    private static void setBadgeOfDefault(Context context,Notification notification,int NOTIFI_ID,int num){
 
        try {
            Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
            intent.putExtra("badge_count", num);
            intent.putExtra("badge_count_package_name", context.getPackageName());
            intent.putExtra("badge_count_class_name", getLauncherClassName(context));
            if (canResolveBroadcast(context, intent)) {
                context.sendBroadcast(intent);
            } else {
                Log.e("Default" + " Badge error", "unable to resolve intent: " + intent.toString());
            }
 
            NotificationManager notifyMgr = (NotificationManager)(context.getSystemService(NOTIFICATION_SERVICE));
            if(num!=0)notifyMgr.notify(NOTIFI_ID, notification);else notifyMgr.cancel(NOTIFI_ID);
 
 
        }catch (Exception e){
            e.printStackTrace();
                Log.e("Default" + " Badge error", "set Badge failed");
        }
 
    }

github : https://github.com/Cedric-Xuan/SNSNotificationBadge

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市娇澎,隨后出現(xiàn)的幾起案子笨蚁,更是在濱河造成了極大的恐慌,老刑警劉巖趟庄,帶你破解...
    沈念sama閱讀 210,978評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赚窃,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡岔激,警方通過(guò)查閱死者的電腦和手機(jī)勒极,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)虑鼎,“玉大人辱匿,你說(shuō)我怎么就攤上這事§挪剩” “怎么了匾七?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,623評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)江兢。 經(jīng)常有香客問(wèn)我昨忆,道長(zhǎng),這世上最難降的妖魔是什么杉允? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,324評(píng)論 1 282
  • 正文 為了忘掉前任邑贴,我火速辦了婚禮,結(jié)果婚禮上叔磷,老公的妹妹穿的比我還像新娘拢驾。我一直安慰自己,他們只是感情好改基,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布繁疤。 她就那樣靜靜地躺著,像睡著了一般秕狰。 火紅的嫁衣襯著肌膚如雪稠腊。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,741評(píng)論 1 289
  • 那天鸣哀,我揣著相機(jī)與錄音架忌,去河邊找鬼。 笑死诺舔,一個(gè)胖子當(dāng)著我的面吹牛鳖昌,可吹牛的內(nèi)容都是我干的备畦。 我是一名探鬼主播,決...
    沈念sama閱讀 38,892評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼许昨,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼懂盐!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起糕档,我...
    開(kāi)封第一講書(shū)人閱讀 37,655評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤莉恼,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后速那,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體俐银,經(jīng)...
    沈念sama閱讀 44,104評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年端仰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了捶惜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,569評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡荔烧,死狀恐怖吱七,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鹤竭,我是刑警寧澤踊餐,帶...
    沈念sama閱讀 34,254評(píng)論 4 328
  • 正文 年R本政府宣布,位于F島的核電站臀稚,受9級(jí)特大地震影響吝岭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吧寺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評(píng)論 3 312
  • 文/蒙蒙 一窜管、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧撮执,春花似錦微峰、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,725評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)颜凯。三九已至谋币,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間症概,已是汗流浹背蕾额。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,950評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留彼城,地道東北人诅蝶。 一個(gè)月前我還...
    沈念sama閱讀 46,260評(píng)論 2 360
  • 正文 我出身青樓退个,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親调炬。 傳聞我的和親對(duì)象是個(gè)殘疾皇子语盈,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容