1.添加依赖
implementation "me.leolin:ShortcutBadger:1.1.22@aar"
依赖github地址
https://github.com/leolin310148/ShortcutBadger
2.创建service
public class BadgeIntentService extends IntentService {
private int notificationId = 0;
public BadgeIntentService() {
super("BadgeIntentService");
}
private NotificationManager mNotificationManager;
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
int badgeCount = intent.getIntExtra("badgeCount", 0);
mNotificationManager.cancel(notificationId);
notificationId++;
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setContentTitle("")
.setContentText("")
.setSmallIcon(R.mipmap.ic_launcher);
Notification notification = builder.build();
ShortcutBadger.applyNotification(getApplicationContext(), notification, badgeCount);
mNotificationManager.notify(notificationId, notification);
}
}
}
3.工具类
public class BadgeUtil {
public static void applyBadgeCount(Context context, int badgeCount) {
if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi")) {
// 判断机型是否是小米
context.startService(new Intent(context, BadgeIntentService.class).putExtra("badgeCount", badgeCount));
} else {
ShortcutBadger.applyCount(context, badgeCount);
}
}
public static void removeBadgeCount(Context context) {
ShortcutBadger.removeCount(context);
}
}
4.调用
BadgeUtil.applyBadgeCount(MainActivity.this, 10);//显示角标
BadgeUtil.removeBadgeCount(MainActivity.this);//关闭角标
5.别忘了添加网络权限和声明service