I need to check the current unread notifications for my app and I was using a notification listener service to do this. However this solution seems to continually check for notifications in the background causing huge battery drain issues, 23% background drain overnight to be precise. Is there a way for me to get the active notifications only when the phone is in a certain state (specifically the lock screen)
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);
}
}