nativepush-baidu插件
为NativeScript编写的推送插件代码。
npm i --save nativepush-baidu插件

NativeScript 百度推送插件

为NativeScript编写的推送插件代码。

安装

在命令提示符/终端中,导航到您的应用程序根目录并运行

tns plugin add nativescript-baidu-push

配置

Android

有关如何将Firebase添加到您的项目的信息,请参阅使用Firebase云消息的Android配置

  • 编辑应用程序根目录中的package.json文件,将捆绑标识符更改为与Firebase的项目包名称匹配。例如

    "id": "org.nativescript.PushNotificationApp"
  • 编辑应用程序根目录中的app/App_Resources/Android/app.gradle文件,将应用程序ID更改为与package.json中的捆绑标识符匹配。例如

    android {
    // ...
    defaultConfig {
    applicationId = "org.nativescript.PushNotificationApp"
    }
    // ...
    }
  • 转到应用程序文件夹,并将Android平台添加到应用程序

    tns platform add android
  • 将包含FCM配置的google-settings.json文件添加到应用程序的app/App_Resources/Android文件夹中。如果不添加此文件,则构建Android应用程序将失败。

插件默认使用firebase-messaging SDK的12.0.1版本。如果您需要更改版本,可以添加一个项目扩展属性firebaseMessagingVersion

    // in the root level of /app/App_Resources/Android/app.gradle:
project.ext {
firebaseMessagingVersion = "+" // OR the version you wish
}

iOS

  • 确保您已在Apple开发者账户中设置了一个应用程序,启用了推送通知并进行了配置。更多关于Apple的添加功能文档 > 配置推送通知部分。

  • 编辑应用程序根目录中的package.json文件,将捆绑标识符更改为与App ID匹配。例如

    "id": "org.nativescript.PushNotificationApp"
  • 转到应用程序文件夹,并将iOS平台添加到应用程序

    tns build ios
  • 转到(应用程序文件夹)/platforms/ios,并打开XCode项目。在项目功能选项中启用推送通知。如果您没有XCode,请转到(应用程序文件夹)/platforms/ios/(应用程序文件夹名称),找到*.entitlements文件,并添加以下aps-environment键及其值:

    <plist version="1.0">
    <dict>
    <key>aps-environment</key>
    <string>development</string>
    <key>insBPushAPIKey</key>
    <string>YOUR-BAIDU-API-KEY</string>
    <key>isDevBPushEnvironment</key>
    <boolean>true</boolean>
    </dict>
    </plist>

使用

在Android中使用此插件

在您的视图模型或组件中添加代码以订阅和接收消息(不要忘记在注册方法的选项中输入您的Firebase Cloud Messaging Sender ID

TypeScript

import * as pushPlugin from "nativescript-baidu-push-ins";
private pushSettings = {
senderID: "<ENTER_YOUR_PROJECT_NUMBER>", // Required: setting with the sender/project number
notificationCallbackAndroid: (stringifiedData: String, fcmNotification: any) => {
const notificationBody = fcmNotification && fcmNotification.getBody();
this.updateMessage("Message received!\n" + notificationBody + "\n" + stringifiedData);
}
};
pushPlugin.register(pushSettings, (token: String) => {
alert("Device registered. Access token: " + token);;
}, function() { });

JavaScript

var pushPlugin = require("nativescript-baidu-push-ins");
var pushSettings = {
senderID: "<ENTER_YOUR_PROJECT_NUMBER>", // Required: setting with the sender/project number
notificationCallbackAndroid: function (stringifiedData, fcmNotification) {
var notificationBody = fcmNotification && fcmNotification.getBody();
_this.updateMessage("Message received!\n" + notificationBody + "\n" + stringifiedData);
}
};
pushPlugin.register(pushSettings, function (token) {
alert("Device registered. Access token: " + token);
}, function() { });
  • 在手机或模拟器上运行应用程序

    tns run android
  • 在插件成功订阅接收通知后,访问令牌将写入控制台并在设备上显示。当通知到达时,如果应用程序已关闭,消息将在通知区域显示;如果应用程序已打开,则直接在通知回调Android中处理。

在iOS中使用此插件

在您的视图模型或组件中添加代码以订阅和接收消息

TypeScript

import * as pushPlugin from "nativescript-baidu-push-ins";
const iosSettings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
baiduAPIKey: 'BaiduAPIKey',
notificationCallbackIOS: (message: any) => {
alert("Message received!\n" + JSON.stringify(message));
}
};

pushPlugin.register(iosSettings, (token: String) => {
alert("Device registered. Access token: " + token);

// Register the interactive settings
if(iosSettings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(() => {
alert('Successfully registered for interactive push.');
}, (err) => {
alert('Error registering for interactive push: ' + JSON.stringify(err))
;
});
}
}, (errorMessage: any) => {
alert("Device NOT registered! " + JSON.stringify(errorMessage));
});

pushPlugin.registerBaiduNotificationSettingCallback(function (result) {
alert('REGISTER BAIDU PUSH NOTIFICATION SUCCESS:');
}, function (error) {
alert('REGISTER BAIDU PUSH NOTIFICATION FAILED:');
});

JavaScript

var pushPlugin = require("nativescript-baidu-push-ins");
var iosSettings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: function (data) {
alert("message", "" + JSON.stringify(data));
}
};

pushPlugin.register(iosSettings, function (data) {
alert("Device registered. Access token" + data);

// Register the interactive settings
if(iosSettings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(function() {
alert('Successfully registered for interactive push.');
}, function(err) {
alert('Error registering for interactive push: ' + JSON.stringify(err));
});
}
}, function() { });

pushPlugin.registerBaiduNotificationSettingCallback(function (result) {
alert('REGISTER BAIDU PUSH NOTIFICATION SUCCESS:');
}, function (error) {
alert('REGISTER BAIDU PUSH NOTIFICATION FAILED:');
});
  • 在手机或模拟器上运行应用程序

    tns run ios
  • 提示:安装pusher应用程序以向正在调试的设备发送通知。在“设备推送令牌”字段中粘贴在启动应用程序后在{n} CLI / XCode调试控制台中生成的设备访问令牌。

API参考

方法

register(options, successCallback, errorCallback) - 使用 Apple/Google 推送通知服务订阅设备,以便应用程序接收通知

选项 平台 类型 描述
senderID Android 字符串 FCM 项目的发送者 ID。此选项对于 Android 是必需的。
notificationCallbackAndroid Android 函数 在 Android 上接收到推送时调用的回调函数。
badge iOS 布尔值 启用通过推送通知设置徽章。
sound iOS 布尔值 启用播放声音。
alert iOS 布尔值 启用创建警报。
clearBadge iOS 布尔值 启用在推送注册时清除徽章。
notificationCallbackIOS iOS 函数 在 iOS 上接收到推送时调用的回调函数。
interactiveSettings iOS 对象 当在 iOS 上使用 registerUserNotificationSettings 时使用的交互设置。

交互设置对象 iOS 可以包含以下内容

选项 类型 描述
actions 数组 iOS 交互式通知动作的列表。
categories 数组 iOS 交互式通知类别的列表。

从 iOS 交互设置中的 actions 数组包含

选项 类型 描述
identifier 字符串 必需。动作的字符串标识符。
title 字符串 必需。按钮动作的标题。
activationMode 字符串 设置为“前景”或“后台”以在前景/后台启动应用程序并响应用动。
destructive 布尔值 如果动作是破坏性的,则启用。将动作颜色更改为默认的红色。
authenticationRequired 布尔值 如果设备必须解锁才能执行动作,则启用。
behavior 字符串 如果动作具有不同的行为(例如文本输入),则设置。

从 iOS 交互设置中的 categories 数组包含

选项 类型 描述
identifier 字符串 必需。类别的字符串标识符。
actionsForDefaultContext 数组 必需。动作字符串标识符的数组。
actionsForMinimalContext 数组 必需。动作字符串标识符的数组。

有关 iOS 交互式通知的更多信息,请访问Apple 开发者网站

var settings = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: function(message) {
alert(JSON.stringify(message));
}
};


pushPlugin.register(settings,
// Success callback
function(token){
// Register the interactive settings
if(settings.interactiveSettings) {
pushPlugin.registerUserNotificationSettings(function() {
alert('Successfully registered for interactive push.');
}, function(err) {
alert('Error registering for interactive push: ' + JSON.stringify(err));
});
}
},
// Error Callback
function(error){
alert(error.message);
}
);

unregister(successCallback, errorCallback, options) - 取消订阅设备,以便应用程序停止接收推送通知。选项对象与 register 方法上的相同

参数 平台 类型 描述
successCallback iOS 函数 当应用程序成功取消订阅时调用。有一个包含结果的参数对象。
successCallback Android 函数 当应用程序成功取消订阅时调用。有一个包含结果的字符串参数。
errorCallback Android 函数 当应用程序未成功取消订阅时调用。有一个包含错误的参数。
options Android 函数 当应用程序未成功取消订阅时调用。有一个包含错误的参数。
pushPlugin.unregister(
// Success callback
function(result) {
alert('Device unregistered successfully');
},
// Error Callback
function(errorMessage) {
alert(errorMessage);
},
// The settings from the registration phase
settings
);

areNotificationsEnabled(successCallback) - 检查是否启用了推送通知(仅限 iOS,Android 上始终返回 true)

参数 平台 类型 描述
successCallback iOS/Android 函数 使用包含通知启用检查结果的布尔参数调用。
pushPlugin.areNotificationsEnabled(function(areEnabled) {
alert('Are Notifications enabled: ' + areEnabled);
});

仅Android

已弃用 - onMessageReceived(callback) - 注册在接收到通知时执行的回调函数。您应该从 notificationCallbackAndroid 注册选项中设置此选项

参数 类型 描述
stringifiedData 字符串 包含通知 JSON 数据的字符串。
fcmNotification 对象 iOS/Android

fcmNotification 对象包含以下方法

方法 返回
getBody() 字符串
getBodyLocalizationArgs() String[]
getBodyLocalizationKey() 字符串
getClickAction() 字符串
getColor() 字符串
getIcon() 字符串
getSound() 字符串
getTag() 字符串
getTitle() 字符串
getTitleLocalizationArgs() String[]
getTitleLocalizationKey() 字符串

onTokenRefresh(callback) - 注册在旧令牌被吊销并获得新令牌时执行的回调函数。请注意,令牌不会作为参数传递给回调。如果您需要新的令牌值,您需要再次调用 register 或添加一些本地代码从 FCM 获取令牌

参数 类型 描述
callback 函数 不带参数调用。
pushPlugin.onTokenRefresh(function() {
alert("new token obtained");
});

仅iOS

registerUserNotificationSettings(successCallback, errorCallback) - 用于在 iOS 上注册交互式推送

参数 类型 描述
successCallback 函数 当应用程序成功取消订阅时调用。有一个包含结果的参数对象。
errorCallback 函数 当应用程序未成功取消订阅时调用。有一个包含错误的参数。

故障排除

如果应用程序表现不佳,这里有一些您可以验证的事情

在Android中的故障排除问题

  • 使用tns run android启动应用程序时(即在调试模式并启用实时同步的情况下),一些后台通知可能无法正确接收。这是因为应用程序不是以常规方式启动进行调试的,并且从后台恢复的方式不同。要正确接收所有通知,请停止应用程序(从最近使用的应用程序列表中滑动并删除它),然后通过在设备上点击应用程序图标重新启动它。

  • 自动添加了google-services插件。如果失败,您可以尝试手动添加它

    • 导航到项目文件夹platforms/android/并找到应用程序级别的build.gradle文件
    • google-services插件添加到应用程序build.gradle文件中其他依赖项的列表中
      dependencies {
      // ...
      classpath "com.google.gms:google-services:3.0.0"
      // ...
      }
    • build.gradle文件底部添加以下行以启用Gradle插件
      apply plugin: 'com.google.gms.google-services'
  • 请确保位于platforms/android/build/...的AndroidManifest.xml文件(不要将其添加到您的“App_Resources/Android/AndroidManifest.xml”文件中)包含以下用于注册GCM监听器的代码片段

    <activity android:name="com.telerik.pushplugin.PushHandlerActivity"/>
    <receiver
    android:name="com.google.android.gms.gcm.GcmReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <category android:name="com.pushApp.gcm" />
    </intent-filter>
    </receiver>
    <service
    android:name="com.telerik.pushplugin.PushPlugin"
    android:exported="false" >
    <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
    </service>
  • 请确保位于platforms/android/build/...的AndroidManifest.xml文件包含以下用于推送通知的权限

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

在iOS中的故障排除问题

  • 错误“注册错误:未找到有效的'aps-environment'授权字符串”- 这意味着xcodeproject中的证书设置不正确。打开xcodeproject,修复它们,您甚至可以从xcode运行应用程序以验证其设置是否正确。xcode中的bundle标识符应与项目根目录中package.json文件中的"id"相同。还请确保在项目设置中的“功能”页面已将“推送通知”切换为开启。

使用Firebase云消息的Android配置

Android的nativescript-baidu-push模块依赖于Firebase云消息(FCM) SDK。在下面的步骤中,您将得到指导,以完成一些额外的步骤,以准备您的Android应用程序接收来自FCM的推送通知。

  1. 添加google-services.json文件

    要使用FCM,您需要此文件。它包含您的Firebase项目的配置和凭据。要获取此文件,请按照官方文档中添加Firebase到项目的说明进行操作。滚动到手动添加Firebase部分。

    将文件放置在应用程序的App_Resources/Android文件夹中

  2. 获取FCM服务器密钥(可选)

    此密钥是能够发送程序化推送通知到您的应用程序所必需的。您可以从Firebase项目获取此密钥。

在Android上接收和处理来自FCM的消息

此插件允许处理包含数据通知以及包含两者有效负载密钥的消息,在本文章中这些消息被称作混合。更多关于这些消息的详细信息请参考此处

此插件扩展了FirebaseMessagingService并重写了其onMessageReceived回调。在您的应用程序中,当调用插件的register方法时,您需要使用notificationCallbackAndroid设置。

该模块中回调的行为遵循FCM服务的行文。

处理数据消息

插件中的notificationCallbackAndroid方法在每次收到data通知时被调用。

如果应用程序停止或挂起,则不会构建和放置任何通知。点击应用程序图标将启动应用程序并调用notificationCallbackAndroid回调,您将在此处接收通知数据。

如果应用程序处于活动状态并在前台,则立即调用带有通知数据的notificationCallbackAndroid回调(fcmNotification)。

处理通知消息

如果应用程序处于活动状态并在前台,它将使用两个参数(stringifiedData, fcmNotification)调用notificationCallbackAndroid回调。

如果应用程序在后台,则将通知放入托盘。当点击时,它将启动应用程序,但不调用notificationCallbackAndroid回调。

处理混合消息

混合消息是包含其负载中的数据键和通知键的消息。当收到此类消息时

  • 应用处于前台,将使用参数(stringifiedData, fcmNotification)调用notificationCallbackAndroid回调
  • 应用处于后台,notificationCallbackAndroid回调不会被调用。通知将被放置在系统托盘上。如果点击托盘中的通知,混合消息中的数据部分将在活动意图的extras中可用,并在NativeScript的相应应用程序事件中可用。

以下是在应用程序resume事件中处理数据部分的示例(例如,从通知将应用带到前台)

application.on(application.resumeEvent, function(args) {
if (args.android) {
var act = args.android;
var intent = act.getIntent();
var extras = intent.getExtras();
if (extras) {
// for (var key in extras) {
// console.log(key + ' -> ' + extras[key]);
// }
var msg = extras.get('someKey');
}
}
});

notificationCallbackAndroid回调的参数

根据通知事件和负载,notificationCallbackAndroid回调将使用两个参数调用。

  • stringifiedData - 字符串。通知负载中data值字符串化的JSON表示。
  • fcmNotification - RemoteMessage.Notification。一个表示RemoteMessage.Notification类的对象,可以通过其公开方法访问。如果回调是从带有负载中的notification键的消息调用,则此参数可用。

设置通知图标和颜色

插件自动处理data对象中的某些键,如messagetitlecolorsmallIconlargeIcon,并使用它们在托盘中构建通知条目。

可以在AndroidManifest.xml中的application指令内设置notification消息的自定义默认颜色和图标

<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />

有关更多信息,请访问编辑应用配置文件文章。

贡献

我们喜欢PRs!查看贡献指南。如果您想贡献,但不确定从哪里开始 - 寻找标记为help wanted问题

获取帮助

请仅使用github issues严格用于报告错误请求新功能。对于一般问题和支持,请查看NativeScript社区论坛或在我们的NativeScript社区Slack频道中询问我们的专家。