在我的应用程序中,我可以通过FCM Console向所有用户发送通知。 现在,我希望用户选择他们喜欢或不接收通知,只有喜欢它的用户才会收到通知。
请指导我
答案 0 :(得分:1)
您可以使用 CheckBox
为用户设置是否要接收通知,并将其保存在 Preference
。
实施例: -
在 CheckBox
中放置 Activity/Fragment
,并询问他们是否要接收通知。
在 Activity/Fragment
java
类中添加此代码。
/*Global Variables*/
public static final String PREFS_NAME ="com.pakage.appname";
public static final String SHOULD_NOTIFY= "ShouldNotify";
/*Global Variables*/
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
setShouldNotifyInPref(true);
}
else
{
setShouldNotifyInPref(false);
}
}
}
);
现在主要登录代码: -
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "Message: " + remoteMessage);
if(getShouldNotifyFromPref())
{
//User Wants To Receive Notification
showNotification();
}
else
{
//User Don't Want To Receive Notification
}
}
从共享首选项保存和检索数据的功能: -
<强> Saving Data:-
强>
private void setShouldNotifyInPref(Boolean shouldNotify)
{
SharedPreferences sp = getApplicationContext().getSharedPreferences(PREFS_NAME ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putBoolean(SHOULD_NOTIFY, shouldNotify);
editor.commit();
}
<强> Retrieving Data:-
强>
private Boolean getShouldNotifyFromPref()
{
SharedPreferences sp = getApplicationContext().getSharedPreferences(PREFS_NAME ,Context.MODE_PRIVATE);
return pref.getBoolean(SHOULD_NOTIFY, null);
}