Как отключить уведомление приложения изнутри приложения - PullRequest
0 голосов
/ 22 сентября 2019

Как отключить Уведомление программно из параметров настроек внутри приложения?

Кажется, что подход к созданию канала уведомлений внутри оператора if в слушателе изменения предпочтений делает свою работу.Я обеспокоен тем, что сейчас я создаю несколько каналов уведомлений.

Preference.xml

<PreferenceCategory
    app:key="notification_category"
    app:title="Notification"
    <SwitchPreferenceCompat
         app:key="notification_state"
         app:title="Enable notification message"/>
</PrefenceCategory>

MainActivity.class

boolean mNotificationState;
Notification mNotification;

SharedPreferences.OnSharedPreferenceChangeListener listener;


@Override
protected void onCreate(Bundle saveInstanceState) {
    ...
    // Create notification object.
    mNotification = Notification(this);

    // Prefernce Listener
    listner = (sharedPrefences, s) -> {
        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(); 
}   

Notification.class , содержит метод NotificationChannel, метод уведомления и getNotificationManager (gettter).

private Context mContext;

// Constructor
public Notification(Context context) {
    this.context = context;
}

// Notification channel. 
public void createNotificationChannel() {
    if(Build.VERSION.SDK_INT >= 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;
}

Ответы [ 3 ]

3 голосов
/ 26 сентября 2019

Если в уведомлении нет push-сообщений типа, то:

1. Disable all currently shown notification  and toggle off sharedPrefs value

checkbox.setOnCheckedChangeListener { _, isChecked ->

        if (isChecked) {

            mSharedPrefs.save(MySharedPrefs.NOTIFICATION_ENABLED, true)

        } else {

            NotificationManagerCompat.from(this).cancelAll()

            mSharedPrefs.save(MySharedPrefs.NOTIFICATION_ENABLED, false)

        }

    }

2. Check `MySharedPrefs.NOTIFICATION_ENABLED` state at part of the code where you actually build and show the notification(eg. BroadcastReceiver)

if (mSharedPrefs.getValueBoolean(MySharedPrefs.NOTIFICATION_ENABLED)) {
    val builder = NotificationCompat.Builder(context, Constants.CHANNEL_ID)

     NotificationManagerCompat.from(context).notify(Constants.NOTIFICATION_ID, builder.build())
}

0 голосов
/ 26 сентября 2019

Вы можете сохранить выбор пользователя в общих настройках.Затем проверьте его значение и покажите уведомление, если его значение равно true, иначе не показывайте его.

0 голосов
/ 25 сентября 2019

К сожалению, в Android нет API для отключения уведомлений.Однако вы можете удалить токен GCM / FCM с сервера, чтобы достичь цели.

...