Nativescript:在Android上显示徽章计数

时间:2017-04-28 04:12:38

标签: android push-notification angular2-nativescript

任务:显示在Android应用的启动图标上通过推送通知传递的徽章计数。

设置:Nativescript + Angular2,Firebase

(你不需要在iOS上做任何事情。)

1 个答案:

答案 0 :(得分:1)

注意:只能为某些品牌显示徽章计数。见[1]。您很可能需要这样的手机进行测试(它可以在我的三星手机上使用)。

我已安装并设置了插件nativescript-plugin-firebase(例如,该应用可以接收推送通知,并且徽章计数会显示在iOS上)。

将Android库ShortcutBadger [2]添加到App_Resources/Android/app.gradle中的依赖项:

dependencies {
    compile 'me.leolin:ShortcutBadger:1.1.16@aar'
}

创建广播接收器:

android.support.v4.content.WakefulBroadcastReceiver.extend("<your_package>.BadgeBroadcastReceiver", {

    onReceive: function (context: any, intent: any) {
        if (!isAndroid || intent.getExtras() == null || !intent.hasExtra("gcm.notification.badge")) {
            return;
        }

        let badge = parseInt(intent.getStringExtra("gcm.notification.badge"));
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(context, badge);
    }
});

将以下行添加到代码AndroidManifest.xml中的文件<application>

<receiver android:name="com.stil.app.smartloyalty.BadgeBroadcastReceiver"
          android:enabled="true"
          android:exported="true">
  <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
  </intent-filter>
</receiver>

要重置徽章计数,我在包装应用程序的组件中添加了对resume事件的回调(例如,app.component.ts):

constructor(private authService: AuthService, private notificationService: NotificationService) {
    application.on(application.resumeEvent, () => this.resetUnreadMessageCount());
}

/**
 * Reset the counter of unread messages (in iOS terms: badge count).
 */
resetUnreadMessageCount() {
    if (isAndroid) {
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(application.android.context, 0);
    }
}

[1] How to add a notification badge/count to application icon on Sony Xperia devices?

[2] https://github.com/leolin310148/ShortcutBadger/