Android SDK setup

Welcome to the OneSignal Android SDK setup guide, designed to help you quickly and seamlessly integrate push notifications into your Android app. In this guide, we’ll show you how to add the OneSignal Android Mobile App SDK to your Android or Amazon Kindle Fire Apps using Android Studio.

Setting up push notifications for your Android app using OneSignal

Android push notifications are crucial for maintaining user engagement and boosting retention in your Android app. They enable you to send timely updates, reminders, and tailored messages straight to your users, enhancing both the user experience and the long-term appeal and profitability of your app.

OneSignal leverages Firebase Cloud Messaging (FCM) but is designed to provide even more flexibility and functionality than Firebase’s notification console and API. We support a range of batching mechanisms in addition to features such as Idempotent notifications, Confirmed Delivery, advanced notification personalization and targeting based on real-time user behavior, and unparalleled speed and reliability. All of these features are available on our robust free plan, which has no limits on API calls, push tokens, or push messages.

Requirements

  • Android 5.0+ device or emulator with "Google Play Store (Services)" installed
  • Android Studio
  • Configured OneSignal App and Platform

Preparing your Android app for push notifications

Before you can enable Android push notifications, it's crucial to ensure that your app is correctly configured.

If you have not done so already, follow the configuration steps below to set up your OneSignal account and your Android Firebase Credentials, and configure the necessary permissions in OneSignal to allow your Android app to send push notifications reliably.

Configure your OneSignal app and platform

If your team already created an account with OneSignal, ask to be invited as an admin role so you can setup the app. Otherwise, sign up for a free account at onesignal.com to get started!

Details on configuring your OneSignal app (click to expand)

You can setup multiple platforms (iOS, Android, Web, Email, SMS) within the same OneSignal App under Settings > Platforms. If you want to create a new app select New App/Website. If this is your first OneSignal app, you will see the next page.



Name your app and organization something recognizable, then select the platform to setup. You can always set up more platforms in this OneSignal App later within Settings > Platforms.

Click Next: Configure Your Platform.


To configure your app, follow the prompts based on the platforms you support.

After you setup your credentials, click Save & Continue.

Choose your Apps Target SDK, the click Save & Continue.


Finally, you will be directed to install the SDK and provided your OneSignal App ID. Make sure to save your App ID as you will need it later.

If you need a teammate or your developer to assist, you can click Invite them to the app and select Done when finished.


Continue through the documentation to finish adding OneSignal to your app.

Setup

1. Add SDK

Open your App build.gradle (Module: app) file, add the following to your dependencies section.

A Gradle build defines the project and its tasks and dependencies. Here we are declaring the OneSignal SDK as an external dependancy for the project. For more details, please view Gradle's documentation on Build Scripts.

implementation 'com.onesignal:OneSignal:[5.0.0, 5.99.99]'
implementation("com.onesignal:OneSignal:[5.0.0, 5.99.99]")

👍

Sync Gradle

Make sure to press "Sync Now" on the banner that pops up after saving!

2. Initialization

Important

Add the following code to the onCreate method in your Application class.

The SDK needs an Android Context to listen to foreground changes to the app. An Activity is also a Context so the SDK can utilize it, however if you only initialize OneSignal in MainActivity it may not cover all the entry points to your app. Also, there are edge cases such as the app being cold started but resuming to a specific Activity where it's not going to trigger the onCreate on your MainActivity.

Details on creating an Application Class (click to expand)

Open your main AndroidManifest.xml

Add android:name=".ApplicationClass" to your <application> tag

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test_login_activity">
   <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".ApplicationClass">
        ...
    </application>
</manifest>

Hover over android:name=".ApplicationClass" or press Alt + Enter or Option + Enter and select Create class 'ApplicationClass'.

This will automatically create the class for you. You can do so manually if you choose.

Now add the onCreate method to your new Application class.

import android.app.Application

class ApplicationClass : Application() {
   override fun onCreate() {
      super.onCreate()
      // TODO: Add OneSignal initialization here
   }
}

import android.app.Application;

public class ApplicationClass extends Application {
  
    @Override
    public void onCreate() {
      super.onCreate();
      // TODO: Add OneSignal initialization here
        
    }
}

Your ONESIGNAL_APP_ID can be found in the dashboard Settings > Keys & IDs.

Note that the initialization can fail if 'ONESIGNAL_APP_ID' is null. If you rely on pulling the app ID remotely, make sure it is not null before calling initWithContext.

import android.app.Application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

import com.onesignal.OneSignal
import com.onesignal.debug.LogLevel

// NOTE: Replace the below with your own ONESIGNAL_APP_ID
val ONESIGNAL_APP_ID = "########-####-####-####-############"
  
class ApplicationClass : Application() {
   override fun onCreate() {
      super.onCreate()
        
      // Verbose Logging set to help debug issues, remove before releasing your app.
      OneSignal.Debug.logLevel = LogLevel.VERBOSE

      // OneSignal Initialization
      OneSignal.initWithContext(this, ONESIGNAL_APP_ID)

      // requestPermission will show the native Android notification permission prompt.
      // NOTE: It's recommended to use a OneSignal In-App Message to prompt instead.
      CoroutineScope(Dispatchers.IO).launch {
         OneSignal.Notifications.requestPermission(false)
      }
   }
}

import android.app.Application;
import com.onesignal.OneSignal;
import com.onesignal.debug.LogLevel;
import com.onesignal.Continue;

public class ApplicationClass extends Application {
  
    // NOTE: Replace the below with your own ONESIGNAL_APP_ID
    private static final String ONESIGNAL_APP_ID = "########-####-####-####-############";
  
    @Override
    public void onCreate() {
        super.onCreate();
        
        // Verbose Logging set to help debug issues, remove before releasing your app.
        OneSignal.getDebug().setLogLevel(LogLevel.VERBOSE);
        
        // OneSignal Initialization
        OneSignal.initWithContext(this, ONESIGNAL_APP_ID);
      
        // requestPermission will show the native Android notification permission prompt.
        // NOTE: It's recommended to use a OneSignal In-App Message to prompt instead.
        OneSignal.getNotifications().requestPermission(false, Continue.none());

    }
}

3. Customize default icons

By default, notifications will be shown with a small bell icon in the notification shade. Follow the Customize Notification Icons guide to create your own small and large notification icons for your app.

4. Testing

Run your app on a physical device to make sure it builds correctly.

If you used the provided code, then the requestPermission method, should prompt you to subscribe to push notifications. You can always change this later but for now, click "Allow" to subscribe to push notifications.

Check your OneSignal Dashboard Audience > Subscriptions to see your Subscription and click the options button on the left to set yourself as a Test Subscription.

📘

Troubleshooting

If running into issues, see our Mobile Troubleshooting Guide.

Try our example projects on our Github repository.

If stuck, contact support directly or email [email protected] for help.

For faster assistance, please provide:

  • Your OneSignal App ID
  • Details, logs, and/or screenshots of the issue.
  • Steps to reproduce

Users & subscriptions

Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).

If you need user consent before tracking their data. OneSignal provides user consent methods to help delay initialization of our SDK until consent is provided. See Handling Personal Data for details.

External ID & aliases

When a user downloads and opens your mobile app or uninstalls and re-installs your app on the same device, a Subscription and a User is created within the OneSignal app.

You can identify that user across multiple subscriptions by setting the External ID property. The External ID should be distinct user ID representing a single user. We recommend using the same user ID as in your Integrations or main analytics tool.

When you authenticate users in your app, call our login method at any time to link this subscription to a user.

val externalId = "123456789" // You will supply the external user id to the OneSignal SDK
OneSignal.login(externalId)
String externalId = "123456789"; // You will supply the external id to the OneSignal SDK
OneSignal.login(externalId);

Our mobile SDKs have methods for detecting User state changes that might be helpful for internal tracking.

📘

External ID & custom aliases

If your users have multiple user IDs, we do support additional custom Aliases. However, you should still always set the External ID as this is the main alias we use to identify users. See Users for details.


Add email and phone number subscriptions

Recommended if using email and SMS messaging.

Like push subscriptions, email addresses and phone numbers each are a new subscription within OneSignal. Your email and sms subscriptions will be tied to the same user if created using our SDK or if you setting the External ID. You can Import your current user data and use our APIs and/or SDK methods to capture new email addresses and phone numbers when provided to you by your users.

// Pass in email provided by customer
OneSignal.User.addEmail("[email protected]")

// Pass in phone number provided by customer
OneSignal.User.addSms("+11234567890")
// Pass in email provided by customer
OneSignal.getUser().addEmail("[email protected]");

// Pass in phone number provided by customer
OneSignal.getUser().addSms("+11234567890");

📘

Users & subscriptions

See Users and Subscriptions for more details.

Property & event tags

Tags are custom key : value pairs of String data used for tracking any custom user events and properties. Setting tags is required for more complex Segments and Message Personalization.

For event triggered messages, use tags with Time Operators to note the date and time the event is/occurred and setup automations for sending to those users. See Abandoned Cart Example for details.

OneSignal.User.addTag("key", "value")
OneSignal.getUser().addTag("key", "value");

📘

Data tags

If you want to store custom data within OneSignal for segmentation, message personalization, and event triggered automation, see Tags for details.

Importing users and subscriptions

If you have a list of user data from a previous source, you can import it into OneSignal following our Import guides.


Message configuration

Common setup items to get the most of your integration.

Deep linking

See our Deep Linking guide to set those up for push and other messaging channels.

Android customizations

For a list of other things you can do, see our Android Customizations.



👍

Basic SDK setup complete!

For details on the above methods and other methods available, see our Mobile SDK reference.