开关打开时显示通知

Show notification when switch is on

我在通过开关启动通知时遇到问题。我有一个开关,可用于通过通知启动我的应用程序。但是当我切换它时,通知不会显示,直到我重新启动 activity。如何在切换开关时立即显示通知。 有点像服务 运行 通知。

此外,我还在堆栈溢出和 developer.android 页面上搜索了无数次。尝试了很多答案,但似乎没有任何效果。

这是我用来在 mt SettingsActivity 中通过 sharedpreference 显示通知的代码:

// 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());
}

如果你不太了解我的意思,希望你能帮助我。让我知道,我会尝试重新格式化问题。

谢谢

如果我没理解错的话,您想观察 Switch 的状态变化并根据其新状态显示或隐藏通知。只需将 OnCheckedChangeListener 添加到您的开关并在那里进行适当的显示或隐藏。