← Back to Push Notifications for WordPress
Download the Library
Here is the library to register for push notifications on your website running Push Notifications for WordPress and receive them:
Integrate the Library in Android Studio
- Put the library AAR into the libs folder
- Complete your build.gradle file:
dependencies { // ... implementation 'com.squareup.okhttp3:okhttp:3.10.0' implementation 'com.google.firebase:firebase-messaging:19.0.1' implementation 'com.delitestudio.pushnotifications:pushnotifications:2.2@aar' }
Add the SDK
First, add rules to your root-level build.gradle
file, to include the google-services plugin:
buildscript { // ... dependencies { // ... classpath 'com.google.gms:google-services:4.3.0' } } allprojects { // ... repositories { // ... google() flatDir { dirs 'libs' } } }
Then, in your module Gradle file (usually the app/build.gradle
), add the apply plugin
line at the bottom of the file to enable the Gradle plugin:
apply plugin: 'com.android.application' android { // ... } dependencies { // ... } // ADD THIS AT THE BOTTOM apply plugin: 'com.google.gms.google-services'
Don't forget to create a Firebase Project, see our Configuring Android Push Notifications guide.
Configure the Resources
You must have this entry in res/values/strings.xml
to be able to communicate to Push Notifications for WordPress and receive notifications:
- The receiver class, a fully qualified name of the Activity you want to call when a new notification has been received.
<resources> <string name="receiver_class">[YOUR PACKAGE NAME].MainActivity</string> </resources>
- Then you must provide notification icons (
ic_notification
):- ldpi: 18×18
- mdpi: 24×24
- hdpi: 36×36
- xhdpi: 48×48
Initialize Push Notifications
Add the following calls using the PushNotifications.Builder
to initialize the library with your site’s url:
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); new PushNotifications.Builder(this, "https://[YOUR WORDPRESS SERVER]") .build(); } }
If you want to use our new WordPress REST APIs endpoints:
new PushNotifications.Builder(this, "https://[YOUR WORDPRESS SERVER]") .namespace("wp-json/pnfw/v1") .build();
You can enable OAuth request signing using:
new PushNotifications.Builder(this, "https://[YOUR WORDPRESS SERVER]") .oauth("[CONSUMER_KEY]", "[CONSUMER_SECRET]") .build();
Integrate Push Notifications into Your App's Main Activity
You should run this code each time your app starts, for example, by placing it within your onCreate()
method:
PushNotifications.refreshToken( new PushNotifications.RegisterHandler() { @Override public void onRegistered() { // Successfully registered } @Override public void onRegisterFailed(String message) { // Registration failed } });
If this is the first startup of the app on a given device or if a previous registration failed or the token is expired, this code begins the registration process. If your app has been already registered onRegistered()
is called.
Receiving Push Notifications
If application has not been started and the device receives a push notification, the library will try to load the activity you have configured in your string resources as receiver_class
.
You can retrieve notification data with the following code in the onCreate
:
Bundle extras = getIntent().getExtras(); if (extras != null) { int id = Integer.parseInt(extras.getString(PushNotifications.ID)); String title = extras.getString(PushNotifications.TITLE); ... do something with id and title ... }
And with this other code, called when your activity has been created but in background:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Bundle extras = intent.getExtras(); int id = Integer.parseInt(extras.getString(PushNotifications.ID)); String title = extras.getString(PushNotifications.TITLE); ... do something with id and title ... }
Once started your application can receive Push Notifications and do something with them.
The Push Notifications for WordPress will send two fields, id
and title
of the original WordPress post. Use this code in your activity to retrieve them:
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mIntentReceiver.abortBroadcast(); Bundle extras = intent.getExtras(); int id = Integer.parseInt(extras.getString(PushNotifications.ID)); String title = extras.getString(PushNotifications.TITLE); ... do something with id and title ... } };
You need to add the following lines of code to the Activity to enable the BroadcastReceiver
:
@Override protected void onResume() { super.onResume(); registerReceiver(mIntentReceiver, PushNotifications.getIntentFilter(this)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mIntentReceiver); }
If you cannot receive notifications, check out our FAQs.
Authorization header
You can modify the authorization header of each requests using this method.
PushNotifications.setAuthorization("Bearer mF_s9.B5f-4.1JqM");
Subscribing
This method allows client device to subscribe itself on the server. A user is created with the specified email address and role "App Subscriber." A welcome email is automatically sent to that address with the login details. If an app subscriber was already registered with that email address it is no longer created, but it is associated with the new token.
PushNotifications.link(email, new PushNotifications.LinkHandler() { @Override public void onLinked(String email, Map<String, String> customParameters) { // Do something } @Override public void onLinkFailed(String message) { // Do something with message } });
You can add any custom fields to subscribers using the hook pnfw_register_custom_parameters and use this method:
Map<String, String> customParameters = new HashMap<>(); customParameters.put("key", value); PushNotifications.link(email, customParameters, linkHandler);
Unregistering
This method allows client device to unregister itself from push notifications. If the last token associated with an anonymous user is removed, the user is also removed.
PushNotifications.unregisterToken( new PushNotifications.UnregisterHandler() { @Override public void onUnregistered() { // Do something } @Override public void onUnregisterFailed(String message) { // Do something with message } });
Retrieving Posts
This method returns a list of posts filtered for the saved device token (i.e. user/device). For each post are returned only basic information.
Date timestamp = null; PushNotifications.loadPosts(timestamp, new PushNotifications.PostsLoadHandler() { @Override public void onLoaded(Posts posts) { for (Post post: posts.getPosts()) { // Do something with post } timestamp = posts.getTimestamp(); } @Override public void onUnchanged() { // Post list unchanged since last retrieval } @Override public void onLoadFailed(String message) { // Do something with message } });
Retrieving specific Post
This method returns the details of the specified post.
PushNotifications.loadPost(identifier, new PushNotifications.PostLoadHandler() { @Override public void onLoaded(Post post) { // Do something with post } @Override public void onUnchanged() { // Post unchanged since last retrieval } @Override public void onLoadFailed(String message) { // Do something with message } });
Retrieving Categories
This method allows client device to retrieve the list of post categories.
Date timestamp = null; PushNotifications.loadCategories(timestamp, new PushNotifications.CategoriesLoadHandler() { @Override public void onLoaded(Categories categories) { for (Category category: categories.getCategories()) { // Do something with category } timestamp = categories.getTimestamp(); } @Override public void onUnchanged() { // Category list unchanged since last retrieval } @Override public void onLoadFailed(String message) { // Do something with message } });
Updating Categories
This method allows client device to set posts categories of which wants to receive push notifications.
PushNotifications.updateCategory(identifier, exclude, new PushNotifications.CategoryUpdateHandler() { @Override public void onUpdated() { // Do something } @Override public void onUpdateFailed(String message) { // Do something with message } });
Retrieving User Categories
This method allows client device to retrieve the list of user categories.
Date timestamp = null; PushNotifications.loadUserCategories(timestamp, new PushNotifications.UserCategoriesLoadHandler() { @Override public void onLoaded(UserCategories categories) { for (UserCategory category: categories.getCategories()) { // Do something with category } timestamp = categories.getTimestamp(); } @Override public void onUnchanged() { // Category list unchanged since last retrieval } @Override public void onLoadFailed(String message) { // Do something with message } });
Updating User Categories
This method allows client device to set user categories.
PushNotifications.updateUserCategory(identifier, new PushNotifications.UserCategoryUpdateHandler() { @Override public void onUpdated() { // Do something } @Override public void onUpdateFailed(String message) { // Do something with message } });