关于NotificationListenerService监听时有失败的处理

关于NotificationListenerService监听时有失败的处理
  • 问题由来
    去年进入一家专业做智能穿戴设备的公司,在项目中需要监听系统通知栏变化(主要是IM类app的信息获取到后推送到用户的手环),在继承android系统提供的NotificationListenerService这个类使用时会出现一个问题:应用进程被杀后再次启动时,服务不生效,导致通知栏有内容变更,服务无法感知

  • 解决方法

    • 第一种方法是:重启手机,但是用户体验不好
    • 第二种方法是:在app每次启动时检测NotificationListenerService是否生效,不生效重新开启
  • 代码

public class NotificationCollectorMonitorService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        ensureCollectorRunning();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    //确认NotificationMonitor是否开启
    private void ensureCollectorRunning() {
        ComponentName collectorComponent = new ComponentName(this, NotificationMonitor.class);
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        boolean collectorRunning = false;
        List<ActivityManager.RunningServiceInfo> runningServices = manager.getRunningServices(Integer.MAX_VALUE);
        if (runningServices == null ) {
            return;
        }
        for (ActivityManager.RunningServiceInfo service : runningServices) {
            if (service.service.equals(collectorComponent)) {
                if (service.pid == Process.myPid() ) {
                    collectorRunning = true;
                }
            }
        }
        if (collectorRunning) {
            return;
        }
        toggleNotificationListenerService();
    }
    //重新开启NotificationMonitor
    private void toggleNotificationListenerService() {
        ComponentName thisComponent = new ComponentName(this,  NotificationMonitor.class);
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
  • 代码说明
    • NotificationMonitor为继承NotificationListenerService的具体监听通知的处理类
    • 在Application的 onCreate方法中启动NotificationCollectorMonitorService
startService(new Intent(this, NotificationCollectorMonitorService.class))
  • 不要忘记了在 AndroidManifest.xml注册此服务
    <service android:name=".NotificationCollectorMonitorService"/>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值