使用第三方控件
导入第三方角标库ShortcutBadge
这个库使用各手机厂商系统的角标展示,比较推荐使用。但是小米手机使用的是notification进行推送,区别其他厂商,三方文档有对小米适配,但是使用demo还是无法在小米手机显示角标。
小米手机方案
原因是:app在打开状态下进行推送,系统会认为推送完成,所以不展示。
解决方案:在app关闭后,进行延时推送。并且点击进入app后,角标会自动消失
修改demo中BadgeIntentService
public class BadgeIntentService extends IntentService {
private static final String NOTIFICATION_CHANNEL = "me.leolin.shortcutbadger.example";
private int notificationId = 0;
public BadgeIntentService() {
super("BadgeIntentService");
}
private NotificationManager mNotificationManager;
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@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("12")
.setContentText("12")
.setSmallIcon(R.drawable.ic_launcher);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setupNotificationChannel();
builder.setChannelId(NOTIFICATION_CHANNEL);
}
Notification notification = builder.build();
try {
Class miuiNotificationClass = Class.forName("android.app.MiuiNotification");
Object miuiNotification = miuiNotificationClass.newInstance();
Field field = miuiNotification.getClass().getDeclaredField("messageCount");
field.setAccessible(true);
field.set(miuiNotification, 121);// 设置信息数
field = notification.getClass().getField(&