我正在尝试在我的 React Native 应用程序中实现 azure 推送通知并在 Android 设备上进行测试。
从在 azure 上创建 azure 通知中心、创建 firebase 项目以及在 azure 中使用服务器密钥的所有步骤均已到位。
我面临的问题是在 android/build.gradle 中添加通知中心的依赖项时:
这是 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)
这是 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()
}
}
还有这个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"
}
}
我总是收到以下错误:
FAILURE: Build failed with an exception.
无法解析配置“:react-native-azurenotificationhub:androidApis”的所有依赖项。 不支持在没有明确选择加入的情况下对存储库使用不安全的协议。
切换 Maven 存储库“maven5(http://dl.bintray.com/microsoftazuremobile/SDK)”以重定向到安全协议(如 HTTPS)或允许不安全协议。
有关更多信息,请参阅 https://docs.gradle.org/8.3/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol在 Gradle 文档中。 使用 --stacktrace 选项运行以获取堆栈跟踪。 使用 --info 或 --debug 选项运行以获得更多日志输出。 使用 --scan 运行以获得完整的见解。 在 https://help.gradle.org 获取更多帮助。
5秒内构建失败 错误 安装应用程序失败。命令失败,退出代码 1:gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 失败:构建失败,出现异常。 * 出了什么问题:无法确定任务“:react-native-azurenotificationhub:generateDebugRFile”的依赖关系。 > 无法解析配置“:react-native-azurenotificationhub:androidApis”的所有依赖项。 > 不支持在没有明确选择加入的情况下对存储库使用不安全的协议。 * 尝试: > 切换 Maven 存储库“maven5(http://dl.bintray.com/microsoftazuremobile/SDK)”以重定向到安全协议(如 HTTPS)或允许不安全协议。 > 更多信息请参考 https://docs.gradle.org/8.3/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol 在 Gradle 文档中。 > 使用 --stacktrace 选项运行以获取堆栈跟踪。 > 使用 --info 或 --debug 选项运行以获得更多日志输出。 > 使用 --scan 运行以获得完整的见解。 > 在 https://help.gradle.org 获取更多帮助。 5 秒内构建失败。
有人可以告诉我如何解决这个问题吗? 现在在React Native中我不能再使用react-native-azurenotificationhub了吗?
在
android/build.gradle
文件中,找到 allprojects
块内的 buildscript
块。这是android/build.gradle
的相关部分:
代码:
allprojects {
repositories {
// Ensure you have the following repository in your "allprojects", "repositories" section.
google()
mavenCentral()
}
}
react-native-azurenotificationhub
的正确存储库 URL。它应该看起来像这样:
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
}
}
maven { ... }
块替换为包含 Azure 存储库的 HTTPS URL 的更新块。注意: 如果可能,请切换到支持安全协议(如 HTTPS)的 Maven 存储库。
fetch
API 或类似 axios
的库向 Azure 通知中心 REST API 端点发出 HTTP 请求。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);
}
};
在 React Native 应用程序中如何处理推送通知具有更大的灵活性和控制力。与使用像
react-native-azurenotificationhub
这样的专用库相比,它还需要更多的手动设置和实施。