Android應(yīng)用圖標(biāo)上的小紅點(diǎn)Badge實(shí)踐代碼

現(xiàn)在Android中有許多的應(yīng)用仿蘋(píng)果的在應(yīng)用圖標(biāo)上顯示小紅點(diǎn)。當(dāng)然有著一些手機(jī)ROM對(duì)小紅點(diǎn)的支持,比如小米,三星等。google的api是沒(méi)有提供這項(xiàng)工能的,這項(xiàng)功能一般都是廠商自己定制的,所以讓開(kāi)發(fā)者著實(shí)頭痛,我也是弄了2天,不是所有的機(jī)型都可以.以后再一點(diǎn)點(diǎn)完善吧.希望對(duì)讀文章的人,或也在受此困惑的人有點(diǎn)幫助!

效果圖:(DODO那個(gè)是我的應(yīng)用,小米miui8測(cè)試)

直接上代碼吧,代碼中有注釋:

201772892156855.gif

直接上代碼吧,代碼中有注釋:

BadgeUtil類(lèi):

public class BadgeUtil {
private BadgeUtil() throws InstantiationException {
throw new InstantiationException("This class is not for instantiation");
}

/**
 * 設(shè)置Badge 目前支持Launcher
 */
public static void setBadgeCount(Context context, int count, int iconResId) {
    if (count <= 0) {
        count = 0;
    } else {
        count = Math.max(0, Math.min(count, 99));
    }

    if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
        setBadgeOfMIUI(context, count, iconResId);
    } else if (Build.MANUFACTURER.equalsIgnoreCase("sony")) {
        setBadgeOfSony(context, count);
    } else if (Build.MANUFACTURER.toLowerCase().contains("samsung") ||
            Build.MANUFACTURER.toLowerCase().contains("lg")) {
        setBadgeOfSumsung(context, count);
    } else if (Build.MANUFACTURER.toLowerCase().contains("htc")) {
        setBadgeOfHTC(context, count);
    } else if (Build.MANUFACTURER.toLowerCase().contains("nova")) {
        setBadgeOfNova(context, count);
    }else if (Build.MANUFACTURER.toLowerCase().contains("OPPO")) {//oppo
        //setBadgeOfOPPO(context, count);
    }else if (Build.MANUFACTURER.toLowerCase().contains("LeMobile")) {//樂(lè)視

    }
    else if (Build.MANUFACTURER.toLowerCase().contains("vivo")) {
        setBadgeOfVIVO(context, count);
    }else if (Build.MANUFACTURER.toLowerCase().contains("HUAWEI")||Build.BRAND.equals("Huawei")||Build.BRAND.equals("HONOR")) {//華為
        setHuaweiBadge(context, count);
    }else if (Build.MANUFACTURER.toLowerCase().contains("")) {//魅族

    }else if (Build.MANUFACTURER.toLowerCase().contains("")) {//金立

    }else if (Build.MANUFACTURER.toLowerCase().contains("")) {//錘子

    }else {
        //Toast.makeText(context, "Not Found Support Launcher", Toast.LENGTH_LONG).show();
    }
}

/**
 * 設(shè)置MIUI的Badge
 */
private static void setBadgeOfMIUI(Context context, int count, int iconResId) {
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle("標(biāo)題").setContentText("消息正文").setSmallIcon(iconResId);
    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, count);
    } catch (Exception e) {
        e.printStackTrace();
    }
    mNotificationManager.notify(0, notification);
}

/**
 * 設(shè)置索尼的Badge
 * 需添加權(quán)限:<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
 */
private static void setBadgeOfSony(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);//啟動(dòng)頁(yè)
    localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));//數(shù)字
    localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());//包名
    context.sendBroadcast(localIntent);
}

/**
 * 設(shè)置三星的Badge\設(shè)置LG的Badge
 */
private static void setBadgeOfSumsung(Context context, int count) {
    // 獲取你當(dāng)前的應(yīng)用
    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);
}

/**
 * 設(shè)置HTC的Badge
 */
private static void setBadgeOfHTC(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);
}

/**
 * 設(shè)置Nova的Badge
 */
private static void setBadgeOfNova(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);
}

/**
 * 設(shè)置vivo的Badge :vivoXplay5 vivo x7無(wú)效果
 */
private static void setBadgeOfVIVO(Context context,int count){
    try {
        Intent intent = new Intent("launcher.action.CHANGE_APPLICATION_NOTIFICATION_NUM");
        intent.putExtra("packageName", context.getPackageName());
        String launchClassName = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getClassName();
        intent.putExtra("className", launchClassName); intent.putExtra("notificationNum", count);
        context.sendBroadcast(intent);
    }catch (Exception e){
        e.printStackTrace();
    }
}

/**
 *設(shè)置oppo的Badge :oppo角標(biāo)提醒目前只針對(duì)內(nèi)部軟件還有微信、QQ開(kāi)放,其他的暫時(shí)無(wú)法提供
 */
private static void setBadgeOfOPPO(Context context,int count){
    try {
        Bundle extras = new Bundle();
        extras.putInt("app_badge_count", count);
        context.getContentResolver().call(Uri.parse("content://com.android.badge/badge"), "setAppBadgeCount", String.valueOf(count), extras);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * 設(shè)置華為的Badge :mate8 和華為 p7,honor暢玩系列可以,honor6plus 無(wú)效果
 */
public static void setHuaweiBadge(Context context, int count)
{
    try {
        Bundle bundle = new Bundle();
        bundle.putString("package", context.getPackageName());
        String launchClassName = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent().getClassName();
        bundle.putString("class", launchClassName);
        bundle.putInt("badgenumber", count);
        context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bundle);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void setBadgeOfMadMode(Context context, int count, String packageName, String className) {
    Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
    intent.putExtra("badge_count", count);
    intent.putExtra("badge_count_package_name", packageName);
    intent.putExtra("badge_count_class_name", className);
    context.sendBroadcast(intent);
}

/**
 * 重置Badge
 */
public static void resetBadgeCount(Context context, int iconResId) {
    setBadgeCount(context, 0, iconResId);
}

public static String getLauncherClassName(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setPackage(context.getPackageName());
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (info == null) {
        info = packageManager.resolveActivity(intent, 0);
    }
    return info.activityInfo.name;
}

}

總結(jié):

小米,三星,索尼,htc,朵唯.手中有的手機(jī)基本小紅點(diǎn)功能都是沒(méi)有問(wèn)題的.

oppo:廠商不提供此功能,只對(duì)于市面上排名前5的商用聊天提供,還說(shuō)對(duì)企業(yè)內(nèi)部的im會(huì)提供此功能,不過(guò)必須要集成oppo證書(shū).

華為:與oppo說(shuō)法一樣,但是按上面代碼測(cè)試,華為的部分機(jī)型是可以實(shí)現(xiàn)的.榮耀6和6p沒(méi)有效果.

vivo:部分手機(jī)有效果,vivo xplay5 x7 沒(méi)有效果.

至于錘子,魅族,金立等,網(wǎng)上說(shuō)是不支持此功能的,,因?yàn)闆](méi)有測(cè)試機(jī),并沒(méi)有驗(yàn)證.

樂(lè)視:有自帶效果(沒(méi)有詢(xún)問(wèn)客服,就不給人添亂了!)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容