Diego Somar
Diego Somar

Reputation: 951

How to increase badge count notification in the Android app icon using Ionic 2?

I developed an app for Android using Ionic 2. The app works fine and the notifications are sent correctly to the app. However, always I receive a push notification, the icon badge which counts the notifications does not appear.

I tried a lot, I searched a lot in the internet and none solutions works.

Information:

  1. I have the cordova-plugin-badge installed.
  2. In my app.component.ts I already imported the Badge Plugin: import { Badge } from 'ionic-native';
  3. To test, I set the badge count to 10, with this code: Badge.set(10); - I put this code inside constructor in app.components.ts.

I followed the Ionic tutorial to use the badge.

I tried to develop using the plugin tutorial, but it is not especific to Ionic. Then, I don't know how this can help.

I used the Ionic 2 tutorial to do the push notifications and, how I said, works fine.

Well, the Ionic documentation about the Badge informes that I have to use the Badge.increase(x). I don't know where to put this code. I thought I have to specify: When the notifications comes to the device, then Badge.increase(x). But, I don't know how to do this.

My Push notification code is:

this.push.register().then((t: PushToken) => {
  return this.push.saveToken(t);
}).then((t: PushToken) => {
  console.log('Token saved:', t.token);
});

this.push.rx.notification()
.subscribe((msg) => {
  alert(msg.title + ': ' + msg.text);
  Badge.clear();
});

But this code runs only with the app opened. When I receive a background notification, how to increase the badge?

Another important information:

I emulate the Android using Android Emulator, provided by Android Studio. The device specs.

In the Android Device Monitor, I see this error:

01-25 21:26:54.558: W/PackageManager(6769): Unknown permission com.sec.android.provider.badge.permission.READ in package com.ionicframework.myapp343731
01-25 21:26:54.558: W/PackageManager(6769): Unknown permission com.sec.android.provider.badge.permission.WRITE in package com.ionicframework.myapp343731

The error list continues here.

Try to search for this error in Google. There are few results. Zero results specifics to Ionic. Awesome, huh?

And... I see badge count notifications in Android. Is possible to do this. But, how?

Sorry for my English and the long text.

Thanks!

EDIT 1 --------------------

My environment:

OS: Ubuntu 16.04.1 LTS
node -v: v5.12.0
npm -v: 3.8.6
ionic -v: 2.2.1
cordova -v: 6.4.0
cordova-plugin-badge version: 0.7.4

EDIT 2 --------------------

My PHP code which sends the notification to Ionic via CURL:

$yourApiSecret = "myApiSecret"; // Available in Ionic Dashboard
$androidAppId = "myAndroidAppId"; // Available in Ionic Dashboard
$api_token = "my.api.token"; // Created in Ionic Dashboard

$data = array(
    "tokens" => "send_to_all",
    "profile" => "my_created_profile", //Created in Ionic Dashboard
    "send_to_all" => true,
    "notification" => array(
        'title'     => $title,
        'message'   => $message,
        )
    );

$data_string = json_encode($data);
$ch = curl_init('https://api.ionic.io/push/notifications');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, 
    array(
        'Content-Type: application/json',
        'X-Ionic-Application-Id: '.$androidAppId,
        'Content-Length: ' . strlen($data_string),
        'Authorization: Bearer '.$api_token
        )
    );

$result = curl_exec($ch);

Upvotes: 2

Views: 8859

Answers (2)

yernarun
yernarun

Reputation: 326

you need to send something like this to set badge to 5:

{ "data": {
"badge": "5"},"to" : "your push token"}

notice to make this work for android you should not send notification object with it. Only data. This way android app will wake up. On IOS you can get current badge and increment it using plugin. What I usually do it to calculate the badge on the backend and sent new badge

Upvotes: 1

Blunderfest
Blunderfest

Reputation: 1854

I just recently ran into the same problem. Android does not support badges on push notifications by default. But it can be done: To make this work, you need a combination of ionic-native/badge with push notifications.

Push notifications can be sent as a background notification by setting content_available: 1 in the payload, reference: http://docs.ionic.io/services/push/#ios-background-notifications

Although the link mentions specifically iOS, you can get it to work on Android by using the following payload through Ionic Push notifications:

"notification": {
    "android": {
        "content_available": 1,
        "payload": {
            "badge": 5,
            "title": "Alert",
            "text": "Notifications"
        },
        "data": {
            "badge": 5
        }
    }
}

What this means:

content_available:1 tells the device when receiving the push notification that it's a background notification that should not alert the user. So your app will be able to process the notification without bothering the user.

payload This is a preference, but here's why I have this: there's a magic combination, for me, with these background push notifications. I don't want the user alerted when the app is closed, but I want to handle it when the app is open. You can't put a title and message on a background push notification and still have it silently delivered in the background (at least on Android), so I put this information on the payload and then manually access it.

data This is the magic sauce that allows Android to process this background notification. Using the push plugin ionic provides, the payload structure is extremely pertinent to how the app processes the notification. Here's a good reference: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#notification-vs-data-payloads

Now, to handling the message in the app.

First, make sure you've properly followed the ionic-native/push documentation for setting up the plugin and injecting it into your app.

Define the provider in app.module

import { Badge } from '@ionic-native/badge';

providers: [
    Badge
]

Import all the things you'll need:

import { Push, PushToken, IPushMessage } from '@ionic/cloud-angular';
import { Platform, Events } from 'ionic-angular';
import { Badge } from '@ionic-native/badge';

Inject it:

constructor(
    private badge: Badge
) {}

Use it to handle a payload:

this.push.rx.notification()
    .subscribe((message: IPushMessage) => {
        console.log(message);
        if (message.title && message.text) {
            let notification: AppNotification = {
                title: message.title,
                message: message.text
            };
            // Handle the push notification in app.
        }

        let payload: any = message.payload;
        // Get the badge number off the payload.
        if(payload && payload.badge) {
            // Using the badge plugin, set the badge number.
            this.badge.set(Number(payload.badge));
        }

        if(payload && payload.title && payload.text) {
            let notification: AppNotification = {
                title: payload.title,
                message: payload.text
            };
            // Do something with the background notification if the app is open.
        }
    });

Following the ionic documentation for the badge plugin, when you receive a push notification, you can take the payload data and then use it to set the badge number. Additionally, if you would like you can also handle the push notification in the app.

Hope this helps.

Upvotes: 1

Related Questions