当开关打开时显示通知



我有一个问题,通过开关启动通知。我有一个开关,可以用来通过通知启动我的应用程序。但当我切换它时,通知不会显示,直到我重新启动活动。当我拨动开关时,我怎样才能立即显示通知?有点像服务在运行通知。

我还搜索了堆栈溢出和开发人员。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到您的开关,并做适当的显示或隐藏在那里。

最新更新