最近接到一个 需求,需要把应用内未读消息的数量同步到桌面角标。官网文档是这么写的。
2. 开发者如何自定义角标数
如果开发者不满意默认逻辑,想要自定义角标的数字,可以通过调用接口告知系统,参考代码如下:
try {
Field field = notification.getClass().getDeclaredField(“extraNotification”);
Object extraNotification = field.get(notification);
Method method = extraNotification.getClass().getDeclaredMethod(“setMessageCount”, int.class);
method.invoke(extraNotification, mCount);
} catch (Exception e) {
e.printStackTrace();
}
虽说官网给出方法,但是调用之后一直没效果。结合之前小米推送,猜测有可能跟小米推送提示角标数的原理是一样的,就是角标数量跟通知有关。并且需要app在后台的时候,调用该方法刷新角标。
然后接着往下看。
想法就是监听app在退到后台的时候,调用刷新。
public class BadgeIntentService extends IntentService {
private static final String NOTIFICATION_CHANNEL = "xiaomi";
private int notificationId = 999;
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("app")
.setContentText("未读提醒")
.setSmallIcon(R.drawable.logo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setupNotificationChannel();
builder.setChannelId(NOTIFICATION_CHANNEL);
}
Notification notification = builder.build();
ShortcutBadger.applyNotification(getApplicationContext(), notification, badgeCount);
mNotificationManager.notify(notificationId, notification);
}
}
@TargetApi(Build.VERSION_CODES.O)
private void setupNotificationChannel() {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, "ShortcutBadger Sample",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
}
记得去AndroidManifest中注册 !!
监听的方法放在Appication中去声明。
public class MyApp extends MultiDexApplication implements MultiDexApplication.ActivityLifecycleCallbacks {
private int foregroundCount = 0; // 位于前台的 Activity 的数目
@Override
public void onActivityStarted(Activity activity) {
if (foregroundCount <= 0) {
// 这里处理从后台恢复到前台的逻辑
try {
//需要清除推送接收到的通知,否则计数会重复
MiPushClient.clearNotification(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
}
foregroundCount++;
}
@Override
public void onActivityStopped(Activity activity) {
foregroundCount--;
if (foregroundCount <= 0) {
//这里处理从前台进入到后台的逻辑
try {
startService(
new Intent(getContext(), BadgeIntentService.class).putExtra("badgeCount", count)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
就这些内容了。