android不使用推送,在桌面图标上显示消息数量

         类似于微信、qq等软件,在应用图标上显示未读消息数量,但是有一个缺陷,需要用户启动app,调用消息列表接口,获取消息数量之和才会去更新图标上的数字。

         下载ShortcutBadger 库,android studio直接引用远程库“compile "me.leolin:ShortcutBadger:1.1.17@aar"”,在app启动页面和调用消息列表的节目,当接口返回数据后,直接调用ShortcutBadger.applyCount(context, badgeCount)方法,然后通过一个Service来更新桌面图标上的数字。

这个是需要一个新建一个单独的 Service , 代码如下:

package com.gyjdj.ui;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;

import com.gyjdj.R;

import me.leolin.shortcutbadger.ShortcutBadger;



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 = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                notification = builder.build();
            }
            ShortcutBadger.applyNotification(getApplicationContext(), notification, badgeCount);
            mNotificationManager.notify(notificationId, notification);
        }
    }
}
 
使用service需要在manifest 中注册

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值