How to suppress notification on lock screen in Android 5 (Lollipop) but let it in notification area?

前端 未结 4 1639
旧巷少年郎
旧巷少年郎 2020-12-31 03:45

After upgrade to Android 5.0 Lollipop it started showing automatically ongoing notification on lock screen.

Sometimes users don\'t want to see all of them so they a

4条回答
  •  渐次进展
    2020-12-31 04:39

    I've created a 'LockscreenIntentReceiver' for my ongoing notification that looks like this:


        private class LockscreenIntentReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try { 
                String action = intent.getAction();
                if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                    Log.d(TAG, "LockscreenIntentReceiver: ACTION_SCREEN_OFF");
                    disableNotification();
                } else if (action.equals(Intent.ACTION_USER_PRESENT)){
                    Log.d(TAG, "LockscreenIntentReceiver: ACTION_USER_PRESENT");
                    // NOTE: Swipe unlocks don't have an official Intent/API in android for detection yet,
                    // and if we set ungoing control without a delay, it will get negated before it's created
                    // when pressing the lock/unlock button too fast consequently.
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (NotificationService.this.isNotificationAllowed()) {
                                enableNotification((Context)NotificationService.this);
                            }
                        }
                    }, 800);
                }
            } catch (Exception e) {
                Log.e(TAG, "LockscreenIntentReceiver exception: " + e.toString());
            }
        }
    }
    

    This code will basically remove the ongoing notification when the user locks the phone (removal will be visible very briefly). And once the user unlocks the phone, the ongoing notification will be restored after the delay time (800 ms here). enableNotification() is a method which will create the notification, and call startForeground(). Currently verified to work on Android 7.1.1 .

    You only have to remember to register & unregister the receiver accordingly.

提交回复
热议问题