1

我正在使用 Firebase 通知来通知用户发布到应用程序的新数据。我正在遵循此处给出的示例:https ://github.com/firebase/quickstart-android/tree/master/messaging

虽然,我也在向用户提供偏好。只有当他们选择通过选中CheckBoxPreference.

我已经设置了CheckBoxPreferenceonPreferenceChangeListener成功了。问题是即使CheckBox未选中,用户也会收到通知。

这是我所做的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());
    }

CheckBoxPreference我在上面的代码中明确指定了只有在检查时才应该发送通知。

这是MyFirebaseMessagingService.java文件的代码:

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]

}

我在这里做的是我将remoteMessage作为 Intent 发送到SettingsActivity并在那里的方法中使用它sendNotification()

所以,很明显我想要的是我希望用户只有在他们选择通过检查CheckBoxPreference.

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

4

1 回答 1

2

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

有关我迄今为止看到的最佳解释,请参阅快速启动 repo 上问题的答案:https ://github.com/firebase/quickstart-android/issues/8#issuecomment-221039175

您有几个选项可以让您的逻辑正常工作:

  • 如果用户没有选中该框,则不要发送通知。因此,与其抑制显示,不如不发送它。例如,您可能会发送到只有选择订阅的用户才能订阅的主题。

  • 发送数据消息而不是通知。这确保了您的代码将始终被调用,即使在应用程序处于后台时也是如此。有关通知和数据消息之间区别的更多信息,请参阅消息有效负载中的通知和数据文档。

相关问题:

于 2016-06-11T23:47:20.430 回答