com.google.firebase.iid.InstanceIdResult Java Examples

The following examples show how to use com.google.firebase.iid.InstanceIdResult. 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: LeanplumFcmProvider.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
@Override
public void getCurrentRegistrationIdAndUpdateBackend() {
  FirebaseInstanceId.getInstance().getInstanceId()
      .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
          if (!task.isSuccessful()) {
            Log.e("getInstanceId failed");
            return;
          }
          // Get new Instance ID token
          String tokenId = task.getResult().getToken();
          if (!TextUtils.isEmpty(tokenId)) {
              onRegistrationIdReceived(Leanplum.getContext(), tokenId);
            }
          }
      });
}
 
Example #2
Source File: AboutFragment.java    From lbry-android with MIT License 6 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    Context context = getContext();
    if (context instanceof MainActivity) {
        MainActivity activity = (MainActivity) context;
        LbryAnalytics.setCurrentScreen(activity, "About", "About");

        if (!Lbry.SDK_READY) {
            activity.addSdkStatusListener(this);
        } else {
            onSdkReady();
        }
    }
    FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(Task<InstanceIdResult> task) {
            Helper.setViewText(textFirebaseToken, task.isSuccessful() ? task.getResult().getToken() : getString(R.string.unknown));
        }
    });

}
 
Example #3
Source File: FcmPushProvider.java    From MixPush with Apache License 2.0 6 votes vote down vote up
@Override
    public void register(Context context) {
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
//                            Log.w(TAG, "getInstanceId failed", task.getException());
                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        // Log and toast
//                        String msg = getString(R.string.msg_token_fmt, token);
//                        Log.d(TAG, msg);
//                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });

    }
 
Example #4
Source File: FCMPushManager.java    From imsdk-android with MIT License 6 votes vote down vote up
@Override
public void registerPush(Context context) {
    Logger.i(TAG + "  firebase 注册push fcm ");
    try {
        FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if(!task.isSuccessful()) {
                    Logger.i("获取firebase service token 失败 ");
                } else {
                    String token = task.getResult().getToken();
                    Logger.i("获取firebase service token : " + token);
                    HttpUtil.registPush(token, QTPushConfiguration.getPlatName());
                }
            }
        });
    } catch (Exception e) {
        Logger.i("firebase service getInstanceId failed e : " + e);
    }
}
 
Example #5
Source File: FirebaseMessagingPlugin.java    From cordova-plugin-firebase-messaging with MIT License 6 votes vote down vote up
@CordovaMethod
private void getToken(String type, final CallbackContext callbackContext) {
    if (type != null) {
        callbackContext.sendPluginResult(
            new PluginResult(PluginResult.Status.OK, (String)null));
    } else {
        FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(Task<InstanceIdResult> task) {
                    if (task.isSuccessful()) {
                        callbackContext.success(task.getResult().getToken());
                    } else {
                        callbackContext.error(task.getException().getMessage());
                    }
                }
            });
    }
}
 
Example #6
Source File: RNPushNotification.java    From react-native-push-notification with MIT License 6 votes vote down vote up
@ReactMethod
public void requestPermissions() {
  final RNPushNotificationJsDelivery fMjsDelivery = mJsDelivery;
  
  FirebaseInstanceId.getInstance().getInstanceId()
          .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
              @Override
              public void onComplete(@NonNull Task<InstanceIdResult> task) {
                  if (!task.isSuccessful()) {
                      Log.e(LOG_TAG, "exception", task.getException());
                      return;
                  }

                  WritableMap params = Arguments.createMap();
                  params.putString("deviceToken", task.getResult().getToken());
                  fMjsDelivery.sendEvent("remoteNotificationsRegistered", params);
              }
          });
}
 
Example #7
Source File: NotificationsManager.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Handles notifications with the provided NotificationsHandler class
 *
 * @param context                   Application Context
 * @param notificationsHandlerClass NotificationHandler class used for handling notifications
 */
public static <T extends NotificationsHandler> void handleNotifications(final Context context, final Class<T> notificationsHandlerClass) {

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            setHandler(context, notificationsHandlerClass);

            FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    NotificationsHandler handler = getHandler(context);

                    if (handler != null) {
                        handler.onRegistered(context, instanceIdResult.getToken());
                    }
                }
            });

            return null;
        }
    }.execute();
}
 
Example #8
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String askForNotificationPermission(JSONArray args){
     this.log("askForNotificationPermission", args);
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         String channelName = "Default Name";
         String channelDescription = "Default Description";
         NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
         if (notificationManager != null) {
             NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
             channel.setDescription(channelDescription);
             notificationManager.createNotificationChannel(channel);
         }
    }
    CountlyPush.init(activity.getApplication(), pushTokenTypeVariable);
    FirebaseApp.initializeApp(context);
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w("Tag", "getInstanceId failed", task.getException());
                        return;
                    }
                    String token = task.getResult().getToken();
                    CountlyPush.onTokenRefresh(token);
                }
            });
    return "askForNotificationPermission";
}
 
Example #9
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String askForNotificationPermission(JSONArray args){
     this.log("askForNotificationPermission", args);
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         String channelName = "Default Name";
         String channelDescription = "Default Description";
         NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
         if (notificationManager != null) {
             NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
             channel.setDescription(channelDescription);
             notificationManager.createNotificationChannel(channel);
         }
    }
    CountlyPush.init(activity.getApplication(), pushTokenTypeVariable);
    FirebaseApp.initializeApp(context);
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w("Tag", "getInstanceId failed", task.getException());
                        return;
                    }
                    String token = task.getResult().getToken();
                    CountlyPush.onTokenRefresh(token);
                }
            });
    return "askForNotificationPermission";
}
 
Example #10
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String askForNotificationPermission(JSONArray args){
     this.log("askForNotificationPermission", args);
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         String channelName = "Default Name";
         String channelDescription = "Default Description";
         NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
         if (notificationManager != null) {
             NotificationChannel channel = new NotificationChannel(CountlyPush.CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
             channel.setDescription(channelDescription);
             notificationManager.createNotificationChannel(channel);
         }
    }
    CountlyPush.init(activity.getApplication(), pushTokenTypeVariable);
    FirebaseApp.initializeApp(context);
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w("Tag", "getInstanceId failed", task.getException());
                        return;
                    }
                    String token = task.getResult().getToken();
                    CountlyPush.onTokenRefresh(token);
                }
            });
    return "askForNotificationPermission";
}
 
Example #11
Source File: GoogleMainApplication.java    From traccar-manager-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            broadcastToken(instanceIdResult.getToken());
        }
    });
}
 
Example #12
Source File: FcmRegistrationIntentService.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
@Override
public void onHandleWork(@NonNull Intent intent) {

    // In the (unlikely) event that multiple refresh operations occur simultaneously,
    // ensure that they are processed sequentially.x
    // [START register_for_gcm]
    // Initially this call goes out to the network to retrieve the token, subsequent calls
    // are local.
    // [START get_token]
    try {
        Task<InstanceIdResult> instanceId = FirebaseInstanceId.getInstance().getInstanceId();
        InstanceIdResult result = Tasks.await(instanceId);
        Log.i(TAG, "FCM Registration Token: " + result.getToken());
        if (ApplicationManager.domaine != null && ApplicationManager.userCredentials != null) {
            sendRegistrationToServer(result.getToken());

            // Subscribe to topic channels
            subscribeTopics();
            // [END get_token]

            // Notify UI that registration has completed, so the progress indicator can be hidden.
            Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);

            // [END register_for_fcm]
        }
    } catch (ExecutionException | InterruptedException ei) {
        ei.printStackTrace();
    }
}
 
Example #13
Source File: NotificationsManager.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Stops handling notifications
 *
 * @param context Application Context
 */
public static void stopHandlingNotifications(final Context context) {

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    try {

                        FirebaseInstanceId.getInstance().deleteInstanceId();

                        NotificationsHandler handler = getHandler(context);

                        if (handler != null ) {
                            handler.onUnregistered(context, instanceIdResult.getToken());
                        }
                    } catch (IOException e) {
                        Log.e("NotificationsManager", e.toString());
                    }
                }
            });

            return null;
        }
    }.execute();
}
 
Example #14
Source File: FirebaseRegistrationTokenHandler.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
public void acquireNewToken(final String senderId) {
    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            final String token = instanceIdResult.getToken();
            if (StringUtils.isNotBlank(token)) handleNewToken(senderId, token);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            MobileMessagingLogger.e(TAG, "Error while acquiring token", e);
        }
    });
}
 
Example #15
Source File: Cache.java    From tindroid with Apache License 2.0 5 votes vote down vote up
public static Tinode getTinode() {
    if (sTinode == null) {
        sTinode = new Tinode("Tindroid/" + TindroidApp.getAppVersion(), API_KEY,
                BaseDb.getInstance().getStore(), null);
        sTinode.setOsString(Build.VERSION.RELEASE);

        // Default types for parsing Public, Private fields of messages
        sTinode.setDefaultTypeOfMetaPacket(VxCard.class, PrivateType.class);
        sTinode.setMeTypeOfMetaPacket(VxCard.class);
        sTinode.setFndTypeOfMetaPacket(VxCard.class);

        // Set device language
        sTinode.setLanguage(Locale.getDefault().toString());

        // Keep in app to prevent garbage collection.
        TindroidApp.retainTinodeCache(sTinode);
    }

    FirebaseInstanceId fbId = FirebaseInstanceId.getInstance();
    //noinspection ConstantConditions: Google lies about getInstance not returning null.
    if (fbId != null) {
        fbId.getInstanceId()
            .addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    if (sTinode != null) {
                        sTinode.setDeviceToken(instanceIdResult.getToken());
                    }
                }
            });
    }
    return sTinode;
}
 
Example #16
Source File: AuthUtils.java    From android-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * function to get the firebase instance id
 */
public static void getFirebaseInstanceId() {
    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
            new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String deviceToken = instanceIdResult.getToken();
            firebaseInstanceId = deviceToken;
            Log.i("fcmId", deviceToken);
        }
    });
}
 
Example #17
Source File: FirebaseMessagingPlugin.java    From cordova-plugin-firebase-messaging with MIT License 5 votes vote down vote up
@CordovaMethod
private void getInstanceId(final CallbackContext callbackContext) {
    FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(Task<InstanceIdResult> task) {
                if (task.isSuccessful()) {
                    callbackContext.success(task.getResult().getId());
                } else {
                    callbackContext.error(task.getException().getMessage());
                }
            }
        });
}
 
Example #18
Source File: CpnNotificationService.java    From cpn with Apache License 2.0 5 votes vote down vote up
public CpnNotificationService() {
    initialise();
    FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
            if (!task.isSuccessful()) {
                if (BuildConfig.DEBUG) {
                    Log.w("CPN", "getInstanceId failed", task.getException());
                }
                return;
            }
            // Get new Instance ID token
            InstanceIdResult token = task.getResult();
            // Log and toast
            if (token == null) {
                if (BuildConfig.DEBUG) {
                    Log.d("CPN", "Token is null");
                }
                return;
            }
            onNewToken(token.getToken());
            if (BuildConfig.DEBUG) {
                Log.d("CPN", token.getToken());
            }
        }
    });
}
 
Example #19
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  final ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
  setContentView(binding.getRoot());

  mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  mInAppMessaging = FirebaseInAppMessaging.getInstance();

  mInAppMessaging.setAutomaticDataCollectionEnabled(true);
  mInAppMessaging.setMessagesSuppressed(false);

  binding.eventTriggerButton.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              mFirebaseAnalytics.logEvent("engagement_party", new Bundle());
              Snackbar.make(view, "'engagement_party' event triggered!", Snackbar.LENGTH_LONG)
                  .setAction("Action", null)
                  .show();
            }
          });

  // Get and display/log the Instance ID
  FirebaseInstanceId.getInstance().getInstanceId()
          .addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
              String instanceId = instanceIdResult.getId();
              binding.instanceIdText.setText(getString(R.string.instance_id_fmt, instanceId));
              Log.d(TAG, "InstanceId: " + instanceId);
            }
          });
}
 
Example #20
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void logInstanceIdToken() {
    // [START log_iid_token]
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task) {
                    Log.d("IID_TOKEN", task.getResult().getToken());
                }
            });
    // [END log_iid_token]
}
 
Example #21
Source File: ReactNativeRegistrationIntentService.java    From react-native-azurenotificationhub with MIT License 4 votes vote down vote up
@Override
protected void onHandleWork(Intent intent) {
    final Intent event = ReactNativeNotificationHubUtil.IntentFactory.createIntent(TAG);
    final ReactNativeNotificationHubUtil notificationHubUtil = ReactNativeNotificationHubUtil.getInstance();
    final String connectionString = notificationHubUtil.getConnectionString(this);
    final String hubName = notificationHubUtil.getHubName(this);
    final String storedToken = notificationHubUtil.getFCMToken(this);
    final String[] tags = notificationHubUtil.getTags(this);
    final boolean isTemplated = notificationHubUtil.isTemplated(this);
    final String templateName = notificationHubUtil.getTemplateName(this);
    final String template = notificationHubUtil.getTemplate(this);

    if (connectionString == null || hubName == null) {
        // The intent was triggered when no connection string has been set.
        // This is likely due to an InstanceID refresh occurring while no user
        // registration is active for Azure Notification Hub.
        return;
    }

    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
            mPool, new OnSuccessListener<InstanceIdResult>() {
                @Override
                public void onSuccess(InstanceIdResult instanceIdResult) {
                    try {
                        String regID = notificationHubUtil.getRegistrationID(ReactNativeRegistrationIntentService.this);
                        String token = instanceIdResult.getToken();
                        Log.d(TAG, "FCM Registration Token: " + token);

                        // Storing the registration ID indicates whether the generated token has been
                        // sent to your server. If it is not stored, send the token to your server.
                        // Also check if the token has been compromised and needs refreshing.
                        if (regID == null || storedToken != token) {
                            NotificationHub hub = ReactNativeUtil.createNotificationHub(hubName, connectionString,
                                    ReactNativeRegistrationIntentService.this);
                            Log.d(TAG, "NH Registration refreshing with token : " + token);

                            if (isTemplated) {
                                regID = hub.registerTemplate(
                                        token, templateName, template, tags).getRegistrationId();
                            } else {
                                regID = hub.register(token, tags).getRegistrationId();
                            }

                            Log.d(TAG, "New NH Registration Successfully - RegId : " + regID);

                            notificationHubUtil.setRegistrationID(ReactNativeRegistrationIntentService.this, regID);
                            notificationHubUtil.setFCMToken(ReactNativeRegistrationIntentService.this, token);

                            event.putExtra(
                                    ReactNativeConstants.KEY_INTENT_EVENT_NAME,
                                    ReactNativeConstants.EVENT_AZURE_NOTIFICATION_HUB_REGISTERED);
                            event.putExtra(
                                    ReactNativeConstants.KEY_INTENT_EVENT_TYPE,
                                    ReactNativeConstants.INTENT_EVENT_TYPE_STRING);
                            event.putExtra(
                                    ReactNativeConstants.KEY_INTENT_EVENT_STRING_DATA, regID);
                            ReactNativeNotificationsHandler.sendBroadcast(
                                    ReactNativeRegistrationIntentService.this, event, 0);

                            // Create notification handler
                            ReactNativeFirebaseMessagingService.createNotificationChannel(
                                    ReactNativeRegistrationIntentService.this);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to complete token refresh", e);

                        event.putExtra(
                                ReactNativeConstants.KEY_INTENT_EVENT_NAME,
                                ReactNativeConstants.EVENT_AZURE_NOTIFICATION_HUB_REGISTERED_ERROR);
                        event.putExtra(
                                ReactNativeConstants.KEY_INTENT_EVENT_TYPE,
                                ReactNativeConstants.INTENT_EVENT_TYPE_STRING);
                        event.putExtra(ReactNativeConstants.KEY_INTENT_EVENT_STRING_DATA, e.getMessage());
                        ReactNativeNotificationsHandler.sendBroadcast(
                                ReactNativeRegistrationIntentService.this, event, 0);
                    }
                }
            });
}
 
Example #22
Source File: AeroGearFCMPushRegistrarTest.java    From aerogear-android-push with Apache License 2.0 4 votes vote down vote up
public StubInstanceIDProvider() {
    Task<InstanceIdResult> mockInstanceIdTask = mock(Task.class);
    when(mockInstanceIdTask.isComplete()).thenReturn(true);
    when(mockInstanceIdTask.isSuccessful()).thenReturn(true);
    when(mockInstanceIdTask.getResult()).thenReturn(new InstanceIdResult() {
        @NonNull
        @Override
        public String getId() {
            return TEST_SENDER_ID;
        }

        @NonNull
        @Override
        public String getToken() {
            return TEMP_ID;
        }
    });
    when(mockInstanceIdTask.addOnCompleteListener((OnCompleteListener<InstanceIdResult>) any())).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {

            Task<InstanceIdResult> completedTask = mock(Task.class);
            when(completedTask.isComplete()).thenReturn(true);
            when(completedTask.isSuccessful()).thenReturn(true);
            when(completedTask.getResult()).thenReturn(new InstanceIdResult() {
                @NonNull
                @Override
                public String getId() {
                    return TEST_SENDER_ID;
                }

                @NonNull
                @Override
                public String getToken() {
                    return TEMP_ID;
                }
            });

            OnCompleteListener<InstanceIdResult> listener = (OnCompleteListener<InstanceIdResult>) invocation.getArguments()[0];
            listener.onComplete(completedTask);
            return null;
        }
    });

    when(mock.getInstanceId()).thenReturn(mockInstanceIdTask);
}