How to send onesignal push notification to a specific android device ?

Hello everyone. Today we are going to look at how to send push notifications to a certain android device and display the content of the notification within that device. For this purpose I am going to use java in android studio. To send push notifications to a certain device I will use a python script. To use push notification in the onesignal platform, we must have two accounts. Firebase and  Onesignal. I will show you step by step how to make a firebase installation for an android app. For OneSignal installation, you can use official documentation. After those installations we will be able to send push notifications to the specific mobile device.

1- Firebase account : Onesignal uses firebase to store notifications. You can sign up freely. After you sign in go to https://console.firebase.google.com/ .You should create a project. To do that click add a project then give a name for your project. I am going to name it as onesignaltest.  When you’ve created your project then go to project settings as shown below :

1.0.0 : Firebase Project Settings

Then in the Your apps section we are going to create an android app.

1.0.1 : Firebase Create Android App

When you click the android icon, it will redirect you into the app registration page. Here, it asks for the android project’s package name, an alias, sha-1 . In this case we do not need to fill the sha-1 section.  I created a project in android studio called onesignaltest. It’s package name is com.example.onesignaltest . You can find your own app’s package name through going to mainactivity file. It will be defined at the top of the codes. So enter the informations

just like I did in the below picture :

1.0.2 : Firebase Android App Registration Page

Then Click Register app. It will show the Download config file section. Here we must download the google-service.json file and move it into our android studio project as shown below :

1.0.3 : Firebase Download Config File

Click the Next button. After that we are going to install the firebase SDK plugin into the android studio project. To do that open your android studio project and go to build.gradle (<project>/YourAppName)  file. And copy the below lines of code then paste it into file :

buildscript {
   repositories {
       google()
       mavenCentral()
   }
   dependencies {
       classpath "com.android.tools.build:gradle:7.0.3"
       classpath 'com.google.gms:google-services:4.3.10'
   }
}

And go to build.gradle (Module/YourAppName) .In the plugins and dependencies sections make sure you have lines of code that’s shown below.

plugins {
   id 'com.android.application'
   id 'com.google.gms.google-services'
}

dependencies {
   ...
   implementation 'com.google.firebase:firebase-bom:29.0.3'
   ...
}

Then click Sync Now to synchronize changes. After that go to https://console.firebase.google.com/ and select the Cloud Messaging menu. In this menu there are Server Key and Sender ID. We are going to use these values to integrate our firebase android app with the onesignal.

2- Onesignal account : It has a free version. I think that the free version is enough to learn the usage of onesignal.

So I won’t explain the basic installation steps. The official documentation explains it very well. You can follow the instructions  from : https://documentation.onesignal.com/docs/android-sdk-setup

Now I suppose you’ve set everything in the onesignal website.  So at the end of the day you must have two keys that onesignal provides for you.

1- OneSignal App ID : This is used to access your onesignal app from android studio. It is unique for each app.

2- Rest Api Key : We are going to use this key to send push notifications to the onesignal app over http. It is also unique for each app.

Let’s open our Android Studio with the project that we already created. My project name is onesignaltest. Go to your MainActivity.java file. Import the onesignal library.

import com.onesignal.OneSignal;

Create a variable to keep your OneSignal App ID .

private static final String ONESIGNAL_APP_ID = "########-####-####-####-############";

Then I am going to create a function called Send2OneSignal and initialize the onesignal in there. It will look like this :

public void Send2OneSignal(){
   OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);

   // OneSignal Initialization
   OneSignal.initWithContext(this);
   OneSignal.setAppId(ONESIGNAL_APP_ID);
}

And call this function in the OnCreate method. When you run this android app in an android phone, it will send some information about the phone to the onsignal cloud. OneSignal will store that phone’s name and some information such as LAST ACTIVE, FIRST SESSION, APP VERSION, COUNTRY, PLAYER ID etc. When we try to push notification, it will be sent to every device that runs your android app. 

We can send notifications to a specific device as well. To be able to do that onesignal provides a tag feature. With that feature we can store a tag’s key and it’s value for each user. For example if each of the users has a unique data let’s say username then we can store that info with the tag feature. Then we can send push notifications over http to a specific username by using the username tag. To store each user’s username in a tag we must send tag information from the android studio to the onesignal. When we’ve done this the Send2OneSignal function will be like this :

public void Send2OneSignal(String username){
   OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);

   OneSignal.sendTag("user_name", username);
   // OneSignal Initialization
   OneSignal.initWithContext(this);
   OneSignal.setAppId(ONESIGNAL_APP_ID);
}

So we can send push notifications via http to the onesignal. Notification must be in JSON format. It will look like this :

Header Info : 
Authorization : Basic  OneSignal-Rest-Api-Key

JSON Body : 
{
	"app_id" : "OneSignal App ID",
	"filters" : [ { "field" : "tag" , "key" : "user_name", "relation" : "=", "value" : "vedat123"   }],
	"contents" : { "en" : "This is my notification contents" }, 
	"headings" : { "en" : "This is my notification title" },
	"data" : { "whoami" : "nobody" }
}

I am going to send a push notifications package with a basic python script. I will publish the source code so you can download it.

With the data property in the json body we can send additional messages with the notification. Just enter a key and it’s value. So what will happen when notification comes to a user’s phone?

We can handle the notification click event and also get the additional data from that notification. After adding this feature into the Send2OneSignal function it will be look like this:

public void Send2OneSignal(String username){
   OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
   OneSignal.setNotificationOpenedHandler(
       new OneSignal.OSNotificationOpenedHandler() {
           @Override
           public void notificationOpened(OSNotificationOpenedResult result) {
               JSONObject data = result.getNotification().getAdditionalData();
               if (data != null) {
                   String additionalData = ””;
                   if (data.toString() != “”){
                       try {
                           JSONObject getData = new JSONObject(data.toString());
                           additionalData = getData.getString(“whoami”);
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
               }
           }
       });

   OneSignal.sendTag("user_name", username);
   // OneSignal Initialization
   OneSignal.initWithContext(this);
   OneSignal.setAppId(ONESIGNAL_APP_ID);
}

When we call the Send2OneSignal function with the username parameter in the OnCreate method it will send the username information to the onesignal. When any notification comes,  we can parse and get the additional data value.

You can download the python script from github : https://github.com/vedat73/onesignal-push-notification-sender 

Alright that’s it for this post guys. I hope this article was useful for you, see you soon !

You may also like...