com.google.firebase.messaging.FirebaseMessaging Java Examples

The following examples show how to use com.google.firebase.messaging.FirebaseMessaging. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FCMRegistration.java    From Android-SDK with MIT License 6 votes vote down vote up
static void unregisterDeviceOnFCM(final Context context, final AsyncCallback<Integer> callback)
{
  FirebaseMessaging.getInstance().unsubscribeFromTopic( DEFAULT_TOPIC ).addOnCompleteListener( new OnCompleteListener<Void>()
  {
    @Override
    public void onComplete( @NonNull Task<Void> task )
    {
      if( task.isSuccessful() )
      {
        Log.d( TAG, "Unsubscribed on FCM." );
        if( callback != null )
          callback.handleResponse( 0 );
      }
      else
      {
        Log.e( TAG, "Failed to unsubscribe in FCM.", task.getException() );
        String reason = (task.getException() != null) ? Objects.toString( task.getException().getMessage() ) : "";
        if( callback != null )
          callback.handleFault( new BackendlessFault( "Failed to unsubscribe on FCM. " + reason ) );
      }
    }
  } );
}
 
Example #2
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void sendToCondition() throws FirebaseMessagingException {
  // [START send_to_condition]
  // Define a condition which will send to devices which are subscribed
  // to either the Google stock or the tech industry topics.
  String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

  // See documentation on defining a message payload.
  Message message = Message.builder()
      .setNotification(new Notification(
          "$GOOG up 1.43% on the day",
          "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."))
      .setCondition(condition)
      .build();

  // Send a message to devices subscribed to the combination of topics
  // specified by the provided condition.
  String response = FirebaseMessaging.getInstance().send(message);
  // Response is a message ID string.
  System.out.println("Successfully sent message: " + response);
  // [END send_to_condition]
}
 
Example #3
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void sendToTopic() throws FirebaseMessagingException {
  // [START send_to_topic]
  // The topic name can be optionally prefixed with "/topics/".
  String topic = "highScores";

  // See documentation on defining a message payload.
  Message message = Message.builder()
      .putData("score", "850")
      .putData("time", "2:45")
      .setTopic(topic)
      .build();

  // Send a message to the devices subscribed to the provided topic.
  String response = FirebaseMessaging.getInstance().send(message);
  // Response is a message ID string.
  System.out.println("Successfully sent message: " + response);
  // [END send_to_topic]
}
 
Example #4
Source File: LoginPresenter.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
public void signInWithGoogle(GoogleSignInAccount googleSignInAccount) {
    signInSubscriber = new DefaultSubscriber<String>(view) {
        @Override
        public void onNext(String userId) {
            super.onNext(userId);
            view.navigateToUsers();
            view.hideProgress();

            FirebaseMessaging.getInstance().subscribeToTopic("user_" + userId);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            view.showMessage(R.string.authentication_failed);
            view.hideProgress();
        }
    };
    authManager.signInGoogle(googleSignInAccount, signInSubscriber, createUser);
}
 
Example #5
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void sendAll() throws FirebaseMessagingException {
  String registrationToken = "YOUR_REGISTRATION_TOKEN";

  // [START send_all]
  // Create a list containing up to 500 messages.
  List<Message> messages = Arrays.asList(
      Message.builder()
          .setNotification(new Notification("Price drop", "5% off all electronics"))
          .setToken(registrationToken)
          .build(),
      // ...
      Message.builder()
          .setNotification(new Notification("Price drop", "2% off all books"))
          .setTopic("readers-club")
          .build()
  );

  BatchResponse response = FirebaseMessaging.getInstance().sendAll(messages);
  // See the BatchResponse reference documentation
  // for the contents of response.
  System.out.println(response.getSuccessCount() + " messages were sent successfully");
  // [END send_all]
}
 
Example #6
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void sendMulticast() throws FirebaseMessagingException {
  // [START send_multicast]
  // Create a list containing up to 100 registration tokens.
  // These registration tokens come from the client FCM SDKs.
  List<String> registrationTokens = Arrays.asList(
      "YOUR_REGISTRATION_TOKEN_1",
      // ...
      "YOUR_REGISTRATION_TOKEN_n"
  );

  MulticastMessage message = MulticastMessage.builder()
      .putData("score", "850")
      .putData("time", "2:45")
      .addAllTokens(registrationTokens)
      .build();
  BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
  // See the BatchResponse reference documentation
  // for the contents of response.
  System.out.println(response.getSuccessCount() + " messages were sent successfully");
  // [END send_multicast]
}
 
Example #7
Source File: UsersPresenter.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
public void signOut() {
    view.showProgress(R.string.signing_out);

    signOutSubscriber = new DefaultSubscriber<String>(view) {
        @Override
        public void onNext(String userId) {
            super.onNext(userId);
            view.hideProgress();
            view.navigateToSplash();
            FirebaseMessaging.getInstance().unsubscribeFromTopic("user_" + userId);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            view.showMessage(R.string.sign_out_error);
            view.hideProgress();
        }
    };
    authManager.signOut(signOutSubscriber);
}
 
Example #8
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void subscribeToTopic() throws FirebaseMessagingException {
  String topic = "highScores";
  // [START subscribe]
  // These registration tokens come from the client FCM SDKs.
  List<String> registrationTokens = Arrays.asList(
      "YOUR_REGISTRATION_TOKEN_1",
      // ...
      "YOUR_REGISTRATION_TOKEN_n"
  );

  // Subscribe the devices corresponding to the registration tokens to the
  // topic.
  TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
      registrationTokens, topic);
  // See the TopicManagementResponse reference documentation
  // for the contents of response.
  System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");
  // [END subscribe]
}
 
Example #9
Source File: FirebaseMessagingSnippets.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
public void unsubscribeFromTopic() throws FirebaseMessagingException {
  String topic = "highScores";
  // [START unsubscribe]
  // These registration tokens come from the client FCM SDKs.
  List<String> registrationTokens = Arrays.asList(
      "YOUR_REGISTRATION_TOKEN_1",
      // ...
      "YOUR_REGISTRATION_TOKEN_n"
  );

  // Unsubscribe the devices corresponding to the registration tokens from
  // the topic.
  TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
      registrationTokens, topic);
  // See the TopicManagementResponse reference documentation
  // for the contents of response.
  System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");
  // [END unsubscribe]
}
 
Example #10
Source File: MainApp.java    From BusyBox with Apache License 2.0 6 votes vote down vote up
@Override public void onCreate() {
  super.onCreate();
  MultiDex.install(this);

  // Logging
  if (BuildConfig.DEBUG) {
    Jot.add(new Jot.DebugLogger());
  } else {
    Jot.add(new CrashlyticsLogger());
  }

  // Fabric
  Fabric.with(this, new Crashlytics(), new Answers());
  Analytics.add(AnswersLogger.getInstance());
  // Crashlytics
  Crashlytics.setString("GIT_SHA", BuildConfig.GIT_SHA);
  Crashlytics.setString("BUILD_TIME", BuildConfig.BUILD_TIME);

  FirebaseMessaging.getInstance().subscribeToTopic("main-" + BuildConfig.FLAVOR);
}
 
Example #11
Source File: MainActivity.java    From CloudFunctionsExample with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.subscribe:
            FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications");
            Toast.makeText(MainActivity.this, "Subscribed to Topic: Push Notifications", Toast.LENGTH_SHORT).show();
            break;
        case R.id.unsubscribe:
            FirebaseMessaging.getInstance().unsubscribeFromTopic("pushNotifications");
            Toast.makeText(MainActivity.this, "Unsubscribed to Topic: Push Notifications", Toast.LENGTH_SHORT).show();
            break;
        case R.id.sign_out_menu:
            AuthUI.getInstance().signOut(this);
            break;

        default:
            return super.onOptionsItemSelected(item);

    }
return true;}
 
Example #12
Source File: RelayService.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
String sendAndroidMessage(String apsTokenHex, String encryptedMessage, boolean useSound) {
    Message.Builder messageBuilder = Message.builder();
    Notification notification = new Notification("Bisq", "Notification");
    messageBuilder.setNotification(notification);
    messageBuilder.putData("encrypted", encryptedMessage);
    messageBuilder.setToken(apsTokenHex);
    if (useSound)
        messageBuilder.putData("sound", "default");
    Message message = messageBuilder.build();
    try {
        FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance();
        firebaseMessaging.send(message);
        return SUCCESS;
    } catch (FirebaseMessagingException e) {
        log.error(e.toString());
        e.printStackTrace();
        return "Error: " + e.toString();
    }
}
 
Example #13
Source File: App.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    initRealm();
    initializeInjector();
    initializeLeakDetection();
    networkManager.start();

    if (authManager.isSignedIn()) {
        FirebaseMessaging.getInstance().subscribeToTopic("user_" + authManager.getCurrentUserId());
    }
}
 
Example #14
Source File: FIRMessagingModule.java    From react-native-fcm with MIT License 5 votes vote down vote up
@ReactMethod
public void send(String senderId, ReadableMap payload) throws Exception {
    FirebaseMessaging fm = FirebaseMessaging.getInstance();
    RemoteMessage.Builder message = new RemoteMessage.Builder(senderId + "@gcm.googleapis.com")
    .setMessageId(UUID.randomUUID().toString());

    ReadableMapKeySetIterator iterator = payload.keySetIterator();
    while (iterator.hasNextKey()) {
        String key = iterator.nextKey();
        String value = getStringFromReadableMap(payload, key);
        message.addData(key, value);
    }
    fm.send(message.build());
}
 
Example #15
Source File: FirebaseMessagingPlugin.java    From cordova-plugin-firebase-messaging with MIT License 5 votes vote down vote up
@CordovaMethod
private void subscribe(String topic, final CallbackContext callbackContext) {
    FirebaseMessaging.getInstance().subscribeToTopic(topic)
        .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    callbackContext.success();
                } else {
                    callbackContext.error(task.getException().getMessage());
                }
            }
        });
}
 
Example #16
Source File: App.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
@Override
public void onTerminate() {
    super.onTerminate();
    networkManager.stop();
    if (authManager.isSignedIn()) {
        FirebaseMessaging.getInstance().unsubscribeFromTopic("user_" + authManager.getCurrentUserId());
    }
}
 
Example #17
Source File: FirebaseMessagingPlugin.java    From cordova-plugin-firebase-messaging with MIT License 5 votes vote down vote up
@CordovaMethod
private void unsubscribe(String topic, final CallbackContext callbackContext) {
    FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
        .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    callbackContext.success();
                } else {
                    callbackContext.error(task.getException().getMessage());
                }
            }
        });
}
 
Example #18
Source File: FirestackCloudMessaging.java    From react-native-firestack with MIT License 5 votes vote down vote up
@ReactMethod
public void subscribeToTopic(String topic, final Callback callback) {
    try {
        FirebaseMessaging.getInstance().subscribeToTopic(topic);
        callback.invoke(null,topic);
    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "Firebase token: " + e);
        WritableMap error = Arguments.createMap();
        error.putString("message", e.getMessage());
        callback.invoke(error);

    }
}
 
Example #19
Source File: FirestackCloudMessaging.java    From react-native-firestack with MIT License 5 votes vote down vote up
@ReactMethod
public void unsubscribeFromTopic(String topic, final Callback callback) {
    try {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic);
        callback.invoke(null,topic);
    } catch (Exception e) {
        WritableMap error = Arguments.createMap();
        error.putString("message", e.getMessage());
        callback.invoke(error);
    }
}
 
Example #20
Source File: FirestackCloudMessaging.java    From react-native-firestack with MIT License 5 votes vote down vote up
@ReactMethod
public void send(String senderId, String messageId, String messageType, ReadableMap params, final Callback callback) {
    FirebaseMessaging fm = FirebaseMessaging.getInstance();
    RemoteMessage.Builder remoteMessage = new RemoteMessage.Builder(senderId);
    remoteMessage.setMessageId(messageId);
    remoteMessage.setMessageType(messageType);
    ReadableMapKeySetIterator iterator = params.keySetIterator();
    while (iterator.hasNextKey()) {
        String key = iterator.nextKey();
        ReadableType type = params.getType(key);
        if (type == ReadableType.String) {
            remoteMessage.addData(key, params.getString(key));
            Log.d(TAG, "Firebase send: " + key);
            Log.d(TAG, "Firebase send: " + params.getString(key));
        }
    }
    try {
        fm.send(remoteMessage.build());
        WritableMap res = Arguments.createMap();
        res.putString("status", "success");
        callback.invoke(null, res);
    } catch(Exception e) {
        Log.e(TAG, "Error sending message", e);
        WritableMap error = Arguments.createMap();
        error.putString("code", e.toString());
        error.putString("message", e.toString());
        callback.invoke(error);
    }
}
 
Example #21
Source File: FcmRegistrationIntentService.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
/**
 * Subscribe to any FCM topics of interest, as defined by the TOPICS constant.
 */
// [START subscribe_topics]
private void subscribeTopics() {
    for (String topic : TOPICS) {
        FirebaseMessaging.getInstance().subscribeToTopic(topic);
    }
}
 
Example #22
Source File: NotificationUtil.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * Subscribe to the Topic channels that will be used to send Group notifications
 */
public static void subscribeToTopics(Config config) {
    if (config.areFirebasePushNotificationsEnabled()) {
        FirebaseMessaging.getInstance().subscribeToTopic(
            NOTIFICATION_TOPIC_RELEASE
        );
    }
}
 
Example #23
Source File: NotificationUtil.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * UnSubscribe from all the Topic channels
 */
public static void unsubscribeFromTopics(Config config) {
    if (config.getFirebaseConfig().isEnabled()) {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(
            NOTIFICATION_TOPIC_RELEASE
        );
    }
}
 
Example #24
Source File: FirebaseRegistrationTokenHandler.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
public void cleanupToken(String senderId) {
    if (StringUtils.isBlank(senderId)) {
        return;
    }

    try {
        FirebaseInstanceId.getInstance().deleteToken(senderId, FirebaseMessaging.INSTANCE_ID_SCOPE);
    } catch (IOException e) {
        MobileMessagingLogger.e(TAG, "Error while deleting token", e);
    }
}
 
Example #25
Source File: FCMPlugin.java    From capacitor-fcm with MIT License 5 votes vote down vote up
@PluginMethod()
public void subscribeTo(final PluginCall call) {
    final String topicName = call.getString("topic");

    FirebaseMessaging
            .getInstance()
            .subscribeToTopic(topicName)
            .addOnSuccessListener(aVoid -> {
                JSObject ret = new JSObject();
                ret.put("message", "Subscribed to topic " + topicName);
                call.success(ret);
            })
            .addOnFailureListener(e -> call.error("Cant subscribe to topic" + topicName, e));

}
 
Example #26
Source File: ElectricityApplication.java    From android-things-electricity-monitor with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(
            new CalligraphyConfig.Builder().setDefaultFontPath("minyna.ttf").setFontAttrId(R.attr.fontPath)
                    .build());
    AndroidThreeTen.init(this);
    FirebaseApp.initializeApp(this);
    FirebaseMessaging.getInstance().subscribeToTopic("Power_Notifications");
}
 
Example #27
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void deviceGroupUpstream() {
    // [START fcm_device_group_upstream]
    String to = "a_unique_key"; // the notification key
    AtomicInteger msgId = new AtomicInteger();
    FirebaseMessaging.getInstance().send(new RemoteMessage.Builder(to)
            .setMessageId(String.valueOf(msgId.get()))
            .addData("hello", "world")
            .build());
    // [END fcm_device_group_upstream]
}
 
Example #28
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void sendUpstream() {
    final String SENDER_ID = "YOUR_SENDER_ID";
    final int messageId = 0; // Increment for each
    // [START fcm_send_upstream]
    FirebaseMessaging fm = FirebaseMessaging.getInstance();
    fm.send(new RemoteMessage.Builder(SENDER_ID + "@fcm.googleapis.com")
            .setMessageId(Integer.toString(messageId))
            .addData("my_message", "Hello World")
            .addData("my_action","SAY_HELLO")
            .build());
    // [END fcm_send_upstream]
}
 
Example #29
Source File: FIRMessagingModule.java    From react-native-fcm with MIT License 5 votes vote down vote up
@ReactMethod
public void subscribeToTopic(String topic, Promise promise){
 try {
        FirebaseMessaging.getInstance().subscribeToTopic(topic);
        promise.resolve(null);
    } catch (Exception e) {
        e.printStackTrace();
        promise.reject(null,e.getMessage());
    }
}
 
Example #30
Source File: FIRMessagingModule.java    From react-native-fcm with MIT License 5 votes vote down vote up
@ReactMethod
public void unsubscribeFromTopic(String topic, Promise promise){
 try {
        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic);
        promise.resolve(null);
    } catch (Exception e) {
        e.printStackTrace();
        promise.reject(null,e.getMessage());
    }
}