小红点消息提示

//第三方依赖  消息通知提醒
implementation files('libs/badgeview.jar')
 
 

工具类,如果不全,可以自己再根据机型往里添加,但是,有些手机不支持。

public class BadgeUtil {

    private static Object miuiNotification;

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

    /**
     * 设置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));
        }
        Log.e("TAG",count+"");
        Log.e("TAG","Build.BRAND:   "+Build.BRAND.toString());
        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")) {//乐视

        }
        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")||Build.BRAND.equals("HUAWEI")) {//华为

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

//    /**
//     * 设置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("标题").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);
}

    /**
     * 在小米手机上显示桌面徽标
     *
     * @param context
     * @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) {
//            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);
//        }
//    }
    /**
     * 设置索尼的Badge
     * 需添加权限:&lt;uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" /&gt;
     */
    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);//启动页
        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);
    }

    /**
     * 设置三星的Badge\设置LG的Badge
     */
    private static void setBadgeOfSumsung(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 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);
    }

    /**
     * 设置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);
    }

    /**
     * 设置vivo的Badge :vivoXplay5 vivo x7无效果
     */
    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();
        }
    }

    /**
     *设置oppo的Badge :oppo角标提醒目前只针对内部软件还有微信、QQ开放,其他的暂时无法提供
     */
    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();
        }
    }

    /**
     * 设置华为的Badge :mate8 和华为 p7,honor畅玩系列可以,honor6plus 无效果
     */
    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;
    }
}
 
 

main类中调用

  private Handler handler = new Handler();

    private Runnable runnable = new MyRunnable();

    public class MyRunnable implements Runnable {

        @Override
        public void run() {
            handler.postDelayed(runnable, 5000);

            BadgeUtil.setBadgeCount(getApplicationContext(), getCount(), R.mipmap.ic_launcher);
        }
    }

    private int getCount() {

        return new Random().nextInt(100);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      //这两个可以放在摘出来的activity父类里,然后main去继承父类,避免每一个类都要写
        App.mContext=this;
        App.mBaseActivity=this;
        textview = findViewById(R.id.textview);
//        getint();
//        textview.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent();
////Intent intent = new Intent(Intent.ACTION_VIEW,uri);
//intent.setAction("android.intent.action.VIEW");
//Uri content_url = Uri.parse("http://www.jdyxqq.com/pkg/app-release-v1.0.2.apk");
//intent.setData(content_url);
//intent.setClassName("com.tencent.mtt","com.tencent.mtt.MainActivity");
//                startActivity(intent);
//            }
//        });
        BadgeView badgeView = new com.jauker.widget.BadgeView(MainActivity.this);
        badgeView.setTargetView(textview);
        badgeView.setBadgeCount(5);

        Button start = (Button) findViewById(R.id.start);
        Button stop = (Button) findViewById(R.id.stop);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (handler == null) {
                    handler = new Handler();
                }

                if (runnable == null) {
                    runnable = new MyRunnable();
                }

                handler.post(runnable);
//                BadgeUtil.setBadgeCount(getApplicationContext(), 5, R.mipmap.ic_launcher);
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (handler != null) {
                    BadgeUtil.resetBadgeCount(getApplicationContext(), R.mipmap.ic_launcher);
                    handler.removeCallbacksAndMessages(null);
                    runnable = null;
                    handler = null;
                    Log.e("TAG","清除");
                }
            }
        });


    }

布局就是两个按钮,

注意!只能在启动项中添加调用工具类,否则无效

<activity
    android:name=".MainActivity"
    android:configChanges="locale|keyboard|screenSize"
    android:label="@string/app_name"
    android:screenOrientation="portrait" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.CREATE_SHORTCUT" />
    </intent-filter>
</activity>

完成后,就可以在App上显示消息数量了


在项目中显示小红点消息提醒的话,是另一种方式,可以使用第三方jar包,直接调用就可以,是基于textview的,基本上textview有的参数它都有,但是!需要注意的是,它没有点击事件,如果直接用在控件上,点击事件会无效!需要在做一个透明的控件放在上面,然后展示在透明控件上

转载出处:http://blog.csdn.net/crazy1235/article/details/42262369

    数字提醒大家肯定都见识过。QQ、微信等app中如果有消息或者提醒的时候,就会展现给用户一个红点或者带有数字的点。前段时间微信上流行把自己的头像换成带有数字提醒的头像,让那些有强迫症的人真是抓狂。


    下面我们就看一下怎么在自己的app中实现这种效果。

    开发者当然可以自己用相对布局来实现这样的效果。一个还好,但是多了呢!就会很繁琐。GitHub上有一个开源的第三方控件,叫做BadgeView。使用它可以很方面的实现想要的效果。

    先来怎么使用,简单的三行代码就可以实现数字提醒:

[java]  view plain  copy
  1. BadgeView badgeView = new com.jauker.widget.BadgeView(this);  
  2. badgeView.setTargetView(textView);  
  3. badgeView.setBadgeCount(3);  

    看一下badgeview中常用的方法:

1. setTargetView(View) --> 设置哪个控件显示数字提醒,参数就是一个view对象

2. setBadgeCount(int) --> 设置提醒的数字

3. setBadgeGravity(Gravity) --> 设置badgeview的显示位置

4. setBackgroundColor() --> 设置badgeview的背景色,当然还可以设置背景图片

5. setBackgroundResource() --> 设置背景图片

6. setTypeface() --> 设置显示的字体

7. setShadowLayer() --> 设置字体的阴影

[java]  view plain  copy
  1. badgeView = new BadgeView(this);  
  2.         badgeView.setTargetView(layout);  
  3.         badgeView.setBackground(12, Color.parseColor("#9b2eef"));  
  4.         badgeView.setText("提示");  

[java]  view plain  copy
  1. badgeView = new BadgeView(this);  
  2.         badgeView.setTargetView(layout);  
  3.         badgeView.setBadgeGravity(Gravity.BOTTOM | Gravity.CENTER);  
  4.         badgeView.setBadgeCount(4);  

[java]  view plain  copy
  1. badgeView = new BadgeView(this);  
  2.         badgeView.setTargetView(layout);  
  3.         badgeView.setBadgeGravity(Gravity.TOP | Gravity.LEFT);  
  4.         badgeView.setTypeface(Typeface.create(Typeface.SANS_SERIF,  
  5.                 Typeface.ITALIC));  
  6.         badgeView.setShadowLayer(2, -1, -1, Color.GREEN);  
  7.         badgeView.setBadgeCount(2);  

    实际上BadgeView这个类就是继承TextView的。很多TextView中设置字体的方法都适用于BadgeView。


    OK。效果实现完毕。


    BadgeView下载链接

    badgeview.jar下载

    DEMO下载






猜你喜欢

转载自blog.csdn.net/liu_ser/article/details/79701372
今日推荐