Search code examples
androidnotificationsandroid-preferencespreferencesandroid-push-notification

How can I hide notification, when user select option from my PreferenceActivity(SettingActivity)


I am using Preferences concept for my SettingActivity and I have an SwitchPreference toggle button for notification on/off, but enable to write code for off notification, when user toggle to off notification.


Solution

  • I guess you can do that also by getting the getDefaultSharedPreferences where your preferences are stored by your user settings and if you are using the FCM then here is how you can do that.

     public class MyFirebaseMessagingService extends FirebaseMessagingService {
        private static final String TAG = "MyFirebaseMsgService";
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
         //here decide by getting the value of your preference manager
         SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    
         if (preferences.getBoolean("your_switch", true)){
              // Your switch is on
              displayNotification();
         } else {
              // Your switch is off
              return;
         }
    
      }
    
     }