仅当CheckBoxPreference被选中时才能推送Firebase通知? [英] How to push firebase notification only when CheckBoxPreference is checked?

查看:146
本文介绍了仅当CheckBoxPreference被选中时才能推送Firebase通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase通知,以通知用户有关发布到应用程序的新数据。我按照这里给出的例子: https://github.com/firebase/ quickstart-android / tree / master / messaging

虽然,我也提供给用户的偏好。只有当他们选择通过检查 CheckBoxPreference 时才会收到通知。



我已经设置了 CheckBoxPreference 以及 onPreferenceChangeListener 成功。问题是,即使 CheckBox 没有被选中,用户也会收到通知。

以下是我所做的 SettingsActivity

  public class SettingsActivity extends PreferenceActivity {

private AppCompatDelegate mDelegate;

首选项myPref;

boolean isChecked = true;

private static final String TAG =SettingsActivity;

public static final String RECEIVE_NOTIFS =receiveNotifications;

@Override
protected void onCreate(Bundle savedInstanceState){
// TODO自动生成方法存根
getDelegate()。installViewFactory();
getDelegate()。onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);

getSupportActionBar()。setDisplayHomeAsUpEnabled(true);

myPref =(CheckBoxPreference)findPreference(RECEIVE_NOTIFS);
myPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference,Object o){
isChecked = Boolean.valueOf(o.toString( ));
if(getChecked){
Toast.makeText(getBaseContext(),Checked,Toast.LENGTH_SHORT).show();
if(getIntent()。getExtras() getMessage()。getString(remoteMessage);
sendNotification(remoteMessage);
} else {
Toast.makeText (getBaseContext(),Error!,Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(),Unchecked,Toast.LENGTH_SHORT ).show();
}
返回true;
}
});


$ b public void sendNotification(String messageBody){
Intent intent = new Intent(this,SettingsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 / * Request code * /,intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(FCM Message)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0 / *通知的ID * /,notificationBuilder.build());





$ b

我已经在上面的代码中明确指出,通知应该只在 CheckBoxPreference 被选中。

这里是 MyFirebaseMessagingService.java

  public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG =MyFirebaseMsgService;

/ **
*收到消息时调用。
*
* @param remoteMessage表示从Firebase云消息收到的消息的对象。
* /
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage){
// TODO(developer):在这里处理FCM消息。
//如果应用程序在前台处理数据和通知消息。
//同样,如果您打算根据收到的FCM
//消息生成您自己的通知,那么这里是应该启动的地方。请参阅下面的sendNotification方法。
Log.d(TAG,From:+ remoteMessage.getFrom());
Log.d(TAG,Notification Message Body:+ remoteMessage.getNotification()。getBody());

Intent intent = new Intent(this,SettingsActivity.class);
intent.putExtra(remoteMessage,remoteMessage.getNotification()。getBody());
startActivity(intent);

// [END receive_message]

}

我在这里做的是我将 remoteMessage 作为Intent发送给 SettingsActivity 并在 sendNotification()方法在那里。

所以,显然我想要的是我希望用户得到通知,只有当他们选择通过检查 CheckBoxPreference



请让我在这里做错了什么。

解决方案

使用Firebase通知时,发送的消息是通知消息。当应用程序在前台时,您的代码将处理通知。但是,当应用程序是后台,默认通知中心将处理它。而且由于通知中心对您的复选框一无所知,它将始终显示通知。

请参阅此答案以获得最佳解释到目前为止: https://github.com/firebase/quickstart- android / issue / 8#issuecomment-221039175



你有几个选择让你的逻辑工作:


  • 如果用户未勾选框,则不发送通知。因此,不要禁止显示,只是不要发送。例如,你可能会发送一个只有用户选择订阅的主题。

  • 发送数据消息而不是通知。这确保了您的代码将始终被调用,即使应用程序是背景的。请参阅有关邮件有效负载中的通知和数据的文档,了解更多信息通知和数据消息之间的区别。


    相关问题:


    无法显示接收到的Firebase快速入门示例消息传递通知

    I am using Firebase notifications in order to notify users about new data posted to the app. I'm following the example given here: https://github.com/firebase/quickstart-android/tree/master/messaging

    Although, I am also providing preference to the user. They should get notified only when they chose to get notified by checking the CheckBoxPreference.

    I have set the CheckBoxPreference and also the onPreferenceChangeListener successfully. The problem is that user is getting the notification even when the CheckBox is unchecked.

    Here's what I have done in SettingsActivity:

    public class SettingsActivity extends PreferenceActivity {
    
        private AppCompatDelegate mDelegate;
    
        Preference myPref;
    
        boolean isChecked = true;
    
        private static final String TAG = "SettingsActivity";
    
        public static final String RECEIVE_NOTIFS = "receiveNotifications";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            getDelegate().installViewFactory();
            getDelegate().onCreate(savedInstanceState);
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
    
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            myPref = (CheckBoxPreference) findPreference(RECEIVE_NOTIFS);
            myPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object o) {
                    isChecked = Boolean.valueOf(o.toString());
                    if (isChecked) {
                        Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show();
                        if (getIntent().getExtras() != null) {
                            String remoteMessage = getIntent().getExtras().getString("remoteMessage");
                            sendNotification(remoteMessage);
                        } else {
                            Toast.makeText(getBaseContext(), "Error!", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
            });
    
        }
    
        public void sendNotification(String messageBody) {
            Intent intent = new Intent(this, SettingsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
    
            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("FCM Message")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }
    

    I have clearly specified in above code that notification should be sent only when CheckBoxPreference is checked.

    Here's MyFirebaseMessagingService.java file's code:

    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
        private static final String TAG = "MyFirebaseMsgService";
    
        /**
         * Called when message is received.
         *
         * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
         */
        // [START receive_message]
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            // TODO(developer): Handle FCM messages here.
            // If the application is in the foreground handle both data and notification messages here.
            // Also if you intend on generating your own notifications as a result of a received FCM
            // message, here is where that should be initiated. See sendNotification method below.
            Log.d(TAG, "From: " + remoteMessage.getFrom());
            Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    
            Intent intent = new Intent(this, SettingsActivity.class);
            intent.putExtra("remoteMessage", remoteMessage.getNotification().getBody());
            startActivity(intent);
        }
        // [END receive_message]
    
    }
    

    What I am doing here is I am sending remoteMessage as an Intent to the SettingsActivity and using it in sendNotification() method there.

    So, clearly what I want is I want the user to get notified only when they have chosen to be by checking the CheckBoxPreference.

    Please let me what am I doing wrong here.

    解决方案

    When you use Firebase Notifications, the message that is sent is a notification message. When the app is in the foreground, your code will be handling the notification. But when the app is backgrounded, the default notification center will handle it. And since the notification center knows nothing of your checkbox, it will always display the notification.

    See this answer to an issue on the quickstart repo for the best explanation I've seen so far: https://github.com/firebase/quickstart-android/issues/8#issuecomment-221039175

    You have a few options to get your logic working:

    • don't send a notification if the user hasn't checked the box. So instead of suppressing the display, simply don't send it. For example, you could probably send to a topic to which only users that have opted in subscribe.

    • send a data message instead of a notification. This ensures that your code will always be invoked, even when the app is backgrounded. See the documentation on Notifications and data in the message payload for more on the difference between notifications and data messages.

    Related questions:

    这篇关于仅当CheckBoxPreference被选中时才能推送Firebase通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆