react-nativegradlepush-notificationfirebase-cloud-messagingazure-notificationhub

Azure Push Notification Hub for React Native


I am trying to implement azure push notifications in my react native app and testing it on android devices.

All the steps from creating the azure notification hub on azure, creating a firebase project and using the server key in azure are in place.

The issue that I am facing is when adding the dependency of the notification hubs in android/build.gradle:

This is android/app/build.gradle

apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
  /* Folders */
  //   The root of your project, i.e. where "package.json" lives. Default is '..'
  // root = file("../")
  //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
  // reactNativeDir = file("../node_modules/react-native")
  //   The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
  // codegenDir = file("../node_modules/@react-native/codegen")
  //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
  // cliFile = file("../node_modules/react-native/cli.js")

  /* Variants */
  //   The list of variants to that are debuggable. For those we're going to
  //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
  //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
  // debuggableVariants = ["liteDebug", "prodDebug"]

  /* Bundling */
  //   A list containing the node command and its flags. Default is just 'node'.
  // nodeExecutableAndArgs = ["node"]
  //
  //   The command to run when bundling. By default is 'bundle'
  // bundleCommand = "ram-bundle"
  //
  //   The path to the CLI configuration file. Default is empty.
  // bundleConfig = file(../rn-cli.config.js)
  //
  //   The name of the generated asset file containing your JS bundle
  // bundleAssetName = "MyApplication.android.bundle"
  //
  //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
  // entryFile = file("../js/MyApplication.android.js")
  //
  //   A list of extra flags to pass to the 'bundle' commands.
  //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
  // extraPackagerArgs = []

  /* Hermes Commands */
  //   The hermes compiler command to run. By default it is 'hermesc'
  // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
  //
  //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
  // hermesFlags = ["-O", "-output-source-map"]
}

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

android {
  ndkVersion rootProject.ext.ndkVersion
  buildToolsVersion rootProject.ext.buildToolsVersion
  compileSdk rootProject.ext.compileSdkVersion

  namespace "com.azurenotificationhubpoc"
  defaultConfig {
    applicationId "com.azurenotificationhubpoc"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 1
    versionName "1.0"
  }
  signingConfigs {
    debug {
      storeFile file('debug.keystore')
      storePassword 'android'
      keyAlias 'androiddebugkey'
      keyPassword 'android'
    }
  }
  buildTypes {
    debug {
      signingConfig signingConfigs.debug
    }
    release {
      // Caution! In production, you need to generate your own keystore file.
      // see https://reactnative.dev/docs/signed-apk-android.
      signingConfig signingConfigs.debug
      minifyEnabled enableProguardInReleaseBuilds
      proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
  }
}

dependencies {
  // The version of react-native is set by the React Native Gradle Plugin
  implementation fileTree(dir: "libs", include: ["*.jar"])
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
  implementation 'androidx.appcompat:appcompat:1.1.0'
  implementation 'androidx.core:core-ktx:1.3.2'
  implementation 'com.facebook.react:react-native:+'
  // Firebase Messaging
  implementation 'com.google.firebase:firebase-messaging:19.2.2'
  // Azure Notification Hubs
  implementation 'com.microsoft.azure:notification-hubs-android-sdk:2.0.0'

  if (hermesEnabled.toBoolean()) {
    implementation("com.facebook.react:hermes-android")
  } else {
    implementation jscFlavor
  }
}

apply plugin: 'com.google.gms.google-services'


apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle");
applyNativeModulesAppBuildGradle(project)

and this is android/build.gradle

buildscript {
   ext {
        buildToolsVersion = "34.0.0"
        minSdkVersion = 21
        compileSdkVersion = 34
        targetSdkVersion = 34
        ndkVersion = "25.1.8937393"
        kotlinVersion = "1.8.0"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath("com.android.tools.build:gradle")
        classpath("com.facebook.react:react-native-gradle-plugin")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
        classpath 'com.google.gms:google-services:4.3.3'  // Google Services plugin
    }
}

allprojects {
    repositories {
        // Ensure you have the following repsoitory in your "allprojects", "repositories" section.
        google()
        mavenCentral()
    }
}

and this package.json:

{
  "name": "AzureNotificationHubPoC",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "eslint .",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-firebase/app": "^19.2.2",
    "@react-native-firebase/messaging": "^19.2.2",
    "react": "18.2.0",
    "react-native": "0.73.7",
    "react-native-azurenotificationhub": "^0.9.5-Patched.1",
    "react-native-azurenotificationhub-mavencentral": "^0.9.5-Patched.2"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/preset-env": "^7.20.0",
    "@babel/runtime": "^7.20.0",
    "@react-native/babel-preset": "0.73.21",
    "@react-native/eslint-config": "0.73.2",
    "@react-native/metro-config": "0.73.5",
    "@react-native/typescript-config": "0.73.1",
    "@types/react": "^18.2.6",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.6.3",
    "eslint": "^8.19.0",
    "jest": "^29.6.3",
    "prettier": "2.8.8",
    "react-test-renderer": "18.2.0",
    "typescript": "5.0.4"
  },
  "engines": {
    "node": ">=18"
  }
}

I am always getting the following error:

FAILURE: Build failed with an exception.

Could not resolve all dependencies for configuration ':react-native-azurenotificationhub:androidApis'. Using insecure protocols with repositories, without explicit opt-in, is unsupported.

Switch Maven repository 'maven5(http://dl.bintray.com/microsoftazuremobile/SDK)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols.
For more information, please refer to https://docs.gradle.org/8.3/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol in the Gradle documentation. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. Get more help at https://help.gradle.org.

BUILD FAILED in 5s error Failed to install the app. Command failed with exit code 1: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. * What went wrong: Could not determine the dependencies of task ':react-native-azurenotificationhub:generateDebugRFile'. > Could not resolve all dependencies for configuration ':react-native-azurenotificationhub:androidApis'. > Using insecure protocols with repositories, without explicit opt-in, is unsupported. * Try: > Switch Maven repository 'maven5(http://dl.bintray.com/microsoftazuremobile/SDK)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols. > For more information, please refer to https://docs.gradle.org/8.3/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol in the Gradle documentation. > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 5s.

Can someone please tell me how can I solve this issue ? Could it be now that in react native I can no longer use react-native-azurenotificationhub ?


Solution

  • In the android/build.gradle file, locate the allprojects block within the buildscript block. Here's the relevant part of the android/build.gradle:

    Code:

    allprojects {
        repositories {
            // Ensure you have the following repository in your "allprojects", "repositories" section.
            google()
            mavenCentral()
        }
    }
    

    It should look something like this:

    allprojects {
        repositories {
            // Ensure you have the following repository in your "allprojects", "repositories" section.
            google()
            maven {
                url 'https://dl.bintray.com/microsoftazuremobile/SDK'
            }
            mavenCentral()
            allowInsecureProtocol = true
        }
    }
    

    NOTE: If possible, switch to a Maven repository that supports secure protocols (like HTTPS).

    const sendPushNotification = async (message) => {
      const hubName = 'YourNotificationHubName';
      const endpoint = `https://{your-namespace}.servicebus.windows.net/${hubName}/messages`;
    
      const requestBody = {
        data: {
          message: message
        }
      };
    
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `SharedAccessSignature ${yourSharedAccessSignature}`
        },
        body: JSON.stringify(requestBody)
      });
    
      if (response.ok) {
        console.log('Push notification sent successfully');
      } else {
        console.error('Failed to send push notification:', response.statusText);
      }
    };
    

    It is more flexibility and control over how push notifications are handled in your React Native app. it also requires more manual setup and implementation compared to using a dedicated library like react-native-azurenotificationhub.

    Reference: