Android SDK Setup

Instructions for adding the OneSignal Android Mobile App SDK to your Android or Amazon Kindle Fire Apps using Android Studio.

Requirements

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

Configure your OneSignal App and Platform

Details on configuring your OneSignal App and Platform (click to expand)

If you haven't already, sign up for a free account on onesignal.com.

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 dependancies. 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.

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
const 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(true)
      }
   }
}

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(true, Continue.with(r -> {
            if (r.isSuccess()) {
              if (r.getData()) {
                // `requestPermission` completed successfully and the user has accepted permission
              }
              else {
                // `requestPermission` completed successfully but the user has rejected permission
              }
            }
            else {
              // `requestPermission` completed unsuccessfully, check `r.getThrowable()` for more info on the failure reason
            }
        }));
    }
}

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 change this later.

Check your OneSignal Dashboard Audience > Subscriptions to see your User & Subscription Record.

Then head over to Messages > New Push to Send your first Push Notification from OneSignal.

Please note that Identity Verification is coming soon to v5 of the Android SDK.

📘

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

Recommended

Push permission with In-App Message

You can continue to opt-in users to push via the requestPermission method. However, Apple's Human Interface Guidelines recommends that apps "Create an alert, modal view, or other interface that describes the types of information they want to send and gives people a clear way to opt in or out."

OneSignal provides In-App Messages to meet this recommendation and have a better user experience. This also permits you to ask for permission again in the future, since the native permission prompt is limited to how many times it can show and cannot be shown again if the user clicks deny.

See How to Prompt for Push Permissions with In-App Messages for details on implementing this.

Identify Users

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

OneSignal creates subscription-level records under a unique ID called the subscription_id. A single user can have multiple subscription_id records based on how many devices, email addresses, and phone numbers they use to interact with your app.

If your app has its own login system to track users, call login at any time to link all channels to a single user. For more details, see Aliases & External ID.

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);

Set Email & Phone Number

Recommended for messaging across multiple channels (push, email, sms).

Use the provided SDK methods to capture one or more email/phone numbers for the user. Follow the channel quickstart guides for setup:

// 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");

Add Data Tags

Optional

Tags are custom key : value pairs of String data used for tracking user events and properties. Setting tags is required for more complex segmentation and message personalization.

See Data Tags for more details.

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