Documentation

Setup BroadcastReceiver


Declare a BroadcastReceiver that will receive your push notifications when they arrive. Your app can then execute any relevant action in response, such as displaying a notification, playing a sound, making a request, etc.

Implementation Example


Create a PushReceiver.java file within your app with the following sample code that displays a notification when a push is received:

package {YOUR_PACKAGE_NAME};

import me.pushy.sdk.Pushy;
import android.content.Intent;
import android.graphics.Color;
import android.content.Context;
import android.app.PendingIntent;
import android.media.RingtoneManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.support.v4.app.NotificationCompat;

public class PushReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String notificationTitle = "MyApp";
        String notificationText = "Test notification";

        // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
        if (intent.getStringExtra("message") != null) {
            notificationText = intent.getStringExtra("message");
        }

        // Prepare a notification with vibration, sound and lights
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setAutoCancel(true)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(notificationTitle)
                .setContentText(notificationText)
                .setLights(Color.RED, 1000, 1000)
                .setVibrate(new long[]{0, 400, 250, 400})
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));

        // Automatically configure a Notification Channel for devices running Android O+
        Pushy.setNotificationChannel(builder, context);

        // Get an instance of the NotificationManager service
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

        // Build the notification and display it
        notificationManager.notify(1, builder.build());
    }
}

Make sure to replace {YOUR_PACKAGE_NAME} with your package name, such as com.my.app, and MainActivity with the name of your main activity.


Note: Please make sure to request the android.permission.VIBRATE permission within your AndroidManifest.xml if you'd like the notification to vibrate the device.

Feel free to modify this sample code to suit your own needs. In the next step, we'll take a look at how to parse the incoming payload data sent by your backend server.