Pavillion
Pavillion

Reputation: 87

Show notification when switch is on

I am having an issue with launching a notification via a switch. I have a switch that can be used to launch my app via the notification. But when I toggle it, the notification doesn't show until I restart the activity. How can I get the notification to show immediately when I toggle the switch. Sort of like a service is running notification.

Also I have searched on stack overflow and on the developer.android page numerous times. Have tried lots of answers and nothing seems to work.

Here is the code I used to show notifications via sharedpreference in mt SettingsActivity:

// Persistent notification
SharedPreferences defaultSettings = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = defaultSettings.getBoolean("pref_key_notification_launch", true);

if (notifyEnabled) {
    NotificationCompat.Builder appLaunch = new NotificationCompat.Builder(this);
    appLaunch.setSmallIcon(R.drawable.ic_gesture);
    appLaunch.setContentTitle("Test!");
    appLaunch.setContentText("This is my test notification");
    appLaunch.setAutoCancel(true);
    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    appLaunch.setContentIntent(contentIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, appLaunch.build());
}

I hope you can help me, if you don't quite understand me. Let me know and I'll try to reformat the question.

Thanks

Upvotes: 0

Views: 45

Answers (1)

Nathan Walters
Nathan Walters

Reputation: 4136

If I understand you correctly, you want to watch for a state change of your Switch and show or hide a notification based on its new state. Simply add an OnCheckedChangeListener to your switch and do the appropriate showing or hiding there.

Upvotes: 1

Related Questions