Как исправить экстремальный разряд батареи с помощью сервиса NotificationListener - PullRequest
1 голос
/ 12 ноября 2019

Мне нужно проверить текущие непрочитанные уведомления для моего приложения, и я использовал для этого службу прослушивания уведомлений. Однако это решение, по-видимому, постоянно проверяет наличие уведомлений в фоновом режиме, вызывающих огромные проблемы с разрядкой аккумулятора, 23% фонового расхода за ночь, если быть точным. Есть ли способ получить активные уведомления только тогда, когда телефон находится в определенном состоянии (в частности, экран блокировки)

public class NotificationListener extends NotificationListenerService {

class CancelNotificationReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {
           String action;
           if (intent != null && intent.getAction() != null) {
               action = intent.getAction();
               if (action.equals(ACTION_NLS_CONTROL)) {
                   String command = intent.getStringExtra("command");
                   if (TextUtils.equals(command, "cancel_last")) {
                       if (mCurrentNotifications != null && mCurrentNotificationsCounts >= 1) {
                           StatusBarNotification sbnn = getCurrentNotifications()[mCurrentNotificationsCounts - 1];
                           cancelNotification(sbnn.getPackageName(), sbnn.getTag(), sbnn.getId());
                       }
                   } else if (TextUtils.equals(command, "cancel_all")) {
                       cancelAllNotifications();
                   }
               }
           }
       }

   }

   @Override
   public void onCreate() {
       super.onCreate();
       logNLS("onCreate...");
       IntentFilter filter = new IntentFilter();
       filter.addAction(ACTION_NLS_CONTROL);
       registerReceiver(mReceiver, filter);
       mMonitorHandler.sendMessage(mMonitorHandler.obtainMessage(EVENT_UPDATE_CURRENT_NOS));
   }

   @Override
   public void onDestroy() {
       super.onDestroy();
       unregisterReceiver(mReceiver);
   }

   @Override
   public IBinder onBind(Intent intent) {
       // a.equals("b");
       logNLS("onBind...");
       return super.onBind(intent);
   }

   @Override
   public void onNotificationPosted(StatusBarNotification sbn) {
       updateCurrentNotifications();
       logNLS("onNotificationPosted...");
       logNLS("have " + mCurrentNotificationsCounts + " active notifications");
       mPostedNotification = sbn;

   }

   @Override
   public void onNotificationRemoved(StatusBarNotification sbn) {
       updateCurrentNotifications();
       logNLS("removed...");
       logNLS("have " + mCurrentNotificationsCounts + " active notifications");
       mRemovedNotification = sbn;
   }

   private void updateCurrentNotifications() {
       try {
           StatusBarNotification[] activeNos = getActiveNotifications();
           if (mCurrentNotifications.size() == 0) {
               mCurrentNotifications.add(null);
           }
           mCurrentNotifications.set(0, activeNos);
           mCurrentNotificationsCounts = activeNos.length;
       } catch (Exception e) {
           logNLS("Should not be here!!");
           e.printStackTrace();
       }
   }

   public static StatusBarNotification[] getCurrentNotifications() {
       if (mCurrentNotifications.size() == 0) {
           logNLS("mCurrentNotifications size is ZERO!!");
           return null;
       }
       return mCurrentNotifications.get(0);
   }
}
...