您的位置:首页 > 其它

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

2017-04-03 13:10 761 查看

关于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)) {

4000
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"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: