關於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"/>
