title: How to turn off App notification from inside the app
body: <p>How do you turn off Notification programmatically from a settings options inside an app? </p>
  
  <p>The approach of creating the Notification channel inside an if statement in a Preference change listener seems to be doing the job. I'm concerned that the I'm creating multiple Notification channels now. </p>
  
  <p>Preference.xml</p>
  
  <pre><code>&lt;PreferenceCategory
      app:key="notification_category"
      app:title="Notification"
      &lt;SwitchPreferenceCompat
           app:key="notification_state"
           app:title="Enable notification message"/&gt;
  &lt;/PrefenceCategory&gt;
  </code></pre>
  
  <p><strong>MainActivity.class</strong></p>
  
  <pre><code>boolean mNotificationState;
  Notification mNotification;
  
  SharedPreferences.OnSharedPreferenceChangeListener listener;
  
  
  @Override
  protected void onCreate(Bundle saveInstanceState) {
      ...
      // Create notification object.
      mNotification = Notification(this);
  
      // Prefernce Listener
      listner = (sharedPrefences, s) -&gt; {
          mNotificationState = SharedPreferences.getBoolean("notification_state", true);
      if(mNotificationState) {
          // concerned that a memory leak migh occur.
          notification.createNotificationChannel();
      } else {
          notification.getNotificationManager().cancelAll();
      }
  }
  
  /**
   * registerOnSharedPreferenceChangeListener
   */
  @Override
  public void onResume() {   
      super.onResume();
  PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).registerOnSharedPreferenceChangeListener(listener);
  } 
  
  /*
   * unregisterOnSharedPreferenceChangeListener.
   */
  @Override
  public void onDestroy() {
      PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).unregisterOnSharedPreferenceChangeListener(listener);
      super.onDestroy(); 
  }   
  </code></pre>
  
  <p><strong>Notification.class</strong>, contains a NotificationChannel method, notfication method, and getNotificationManager (gettter).</p>
  
  <pre><code>private Context mContext;
  
  // Constructor
  public Notification(Context context) {
      this.context = context;
  }
  
  // Notification channel. 
  public void createNotificationChannel() {
      if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
          CharSequence name = "notification_ID";
          String description = "My Notificatin";
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
      }
      // Set NotificationChannel ch = new NotificationChannel(NOTIFICATION_ID, name, importance);
      ch.setDescription(description);
  
      // Register the channel.
      notificationManager = context.getSystemService(NotificationManager.class);
  
      notificationManager.createNotificationChannel(ch);
  }
  
  public NotificationManager getNotificationManager() {
      return notificationManager;
  }
  </code></pre>