Java push notifications android

How to Push Notification in Android using Firebase Cloud Messaging?

Firebase Cloud Messaging is a real-time solution for sending notifications to client apps without any kind of charges. FCM can reliably transfer notifications of up to 4Kb of payload. In this article, a sample app showing how this service can be availed is developed. Though FCM also allows sending out notifications using an app server, here Firebase admin SDK is used. Follow the complete article to implement an example of FCM.

Approach

Step 1: Add Firebase to the project and the required permissions To add firebase to the project please refer Adding Firebase to Android App. The following is the gist of adding FCM to the app. Go to Tools -> Firebase -> Cloud Messaging -> Set up Firebase Cloud Messaging

  1. Connect your app to Firebase: Complete the three steps of creating a Firebase project.
  2. Add FCM to the app.

Since receiving FCM notifications require the use of the internet, add the following permission to the AndroidManifest.xml file anywhere between the and tags.

Note: compile ‘…..’ this format for setting up dependencies is deprecated, instead, use implementation ‘…..’ to declare dependencies in case of any discrepancy.

Step 2: Add all the required drawable resources Here, the following icon has been used as a drawable resource. Add all the drawable resources to the drawable resource folder. Step 3: Customize the activity_main.xml Here, the home screen of the app just holds a TextView, however, one can customize the app as per the requirements.

Читайте также:  Azul zulu java 11

Step 4: Create the Notification Layout Create a new notification.xml file to design the layout for the Notification. This step is stated as optional because the content and title too can be directly set too without customizing the appearance of the notification, however here the notification has the following layout. Here the Notification consists of:

Step 5: Create the message receiving class Create a FirebaseMessageReceiver.java class. This class extends the FirebaseMessagingService. Add the following code to the AndroidManifest.xml file between the and tags to recognise the FirebaseMessagingService as a service in the app.

Here the attribute ‘android: name’ is assigned the name of the Java file that extends the FirebaseMessagingService so pass the class name FirebaseMessageReceiver. This service is required to do any type of message handling beyond just receiving notifications, while the client app runs in the background. It also serves the purpose of receiving notifications in foreground apps and much more. The complete AndroidManifest.xml file is given below.

Step 6: Working with FirebaseMessageReceiver.java (Java) or for Kotlin FirebaseMessageReceiver.kt. It overrides the onMessageReceived() method to handle 2 events:

  1. If Notification contains any data payload, i.e it is received from the app server.
  2. If Notification contains any notification payload, i.e. it is sent via the Firebase Admin SDK.

This method takes RemoteMessage as a parameter. RemoteMessage is a class that extends Object Class and implements Parcelable interface. It is nothing but the object of the message passed using FCM. The above method then calls a user-defined method showNotification() which in turn accepts two parameters. A detailed explanation is provided via comments in the code itself. A notification channel is required for Notifications in Android Versions greater than Oreo. In this example, since a customized notification is designed, a method getCustomDesign() is defined and called to set the resources accordingly. This method sets the custom layout for the display of the notification received. Assuming that only title and body are received from the notification, it appropriately maps the TextViews according to the IDs and sets the image resource for the notification. The complete code for this file is given below.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Push Messaging

  • Overview
  • Parse Push
  • Setup
  • Sending Push Notifications
  • Receiving Push Notifications
  • Basic Push Invoking Activity
  • Custom Push Broadcast Receiver
  • Creating Dashboard Notifications
  • Launching an Activity
  • Checking App State when Receiving a Broadcast
  • Source Code
  • Gotchas
  • Google Cloud Messaging
  • References

Finding these guides helpful?

We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.

Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.

Clone this wiki locally

This guide will show you how to configure an Android app to send and receive push notifications. There are several approaches to sending push notifications. The two most common are:

  • Parse Push — Push wrapper around GCM that makes push simple and easy
  • Google Cloud Messaging — The foundation of push messaging in Android

First approach is to use the Parse Push service to send and receive push notifications. You will first need to setup a Parse server by following our configuring parse server guide to get things started.

Start by checking out our push notifications setup guide for Parse to get things started. Use the push notifications client demo as a reference as well.

Sending Push Notifications

Because of the implicit security issues with allowing push notifications to be sent through Android or iOS directly to other devices, this feature is disabled. Normally in hosted Parse you can toggle an option to override this security restriction. For open source Parse, you must implement pre-defined code written in JavaScript that can be called by the clients to execute, otherwise known as Parse Cloud.

Your Java client should call this function:

HashMapString, String> test = new HashMap<>(); test.put("message", "testing"); test.put("customData", "abc"); ParseCloud.callFunctionInBackground("pushChannelTest", test);

You then need to implement a custom Parse function on your cloud server:

Parse.Cloud.define('pushChannelTest', function(request, response)  // request has 2 parameters: params passed by the client and the authorized user var params = request.params; var user = request.user; var message = params.message; var customData = params.customData; // use to custom tweak whatever payload you wish to send var pushQuery = new Parse.Query(Parse.Installation); pushQuery.equalTo("deviceType", "android"); var payload =  "alert": message, "customdata": customData >; >; // Note that useMasterKey is necessary for Push notifications to succeed. Parse.Push.send( where: pushQuery, // for sending to a specific channel data: payload, >,  success: function()  console.log("#### PUSH OK"); >, error: function(error)  console.log("#### PUSH ERROR" + error.message); >, useMasterKey: true>); response.success('success'); >);

Receiving Push Notifications

Check out the Receiving Push Guide for a basic overview of receiving Push messages within an Android app. There are two basic ways to receive push notifications.

Basic Push Invoking Activity

Normally when receiving a push, Parse will open the default activity that is designated as the main launcher in your AndroidManifest.xml file, but you can have Parse trigger a different activity to launch. You can change this behavior by subclassing ParshPushBroadcastReceiver and overriding the getActivity() method to returning the Activity you prefer to launch instead:

import android.app.Activity; public class YourBroadcastReceiver extends ParsePushBroadcastReceiver < . protected Classextends Activity> getActivity(Context context, Intent intent) < return YourActivity.class; // the activity that shows up > . >

You will also need to modify the default Parse Broadcast Receiver normally used and replace with this custom class name.

receiver android:name="your.package.name.YourBroadcastReceiver" android:exported="false" > intent-filter> action android:name="com.parse.push.intent.RECEIVE" /> action android:name="com.parse.push.intent.DELETE" /> action android:name="com.parse.push.intent.OPEN" /> intent-filter> receiver>

This way is pretty straightforward to bringing up an activity when a push is received but you can use a more custom approach if you need more flexibility with how a notification is handled.

Custom Push Broadcast Receiver

Receiving push notifications sent with Parse can also be done using the BroadcastReceiver and implementing the onReceive() method to manage incoming push events. Any activity can register to handle these broadcast events.

If you want to implement the push notification receiver, then check out this tutorial. Full source code for this tutorial can be found on github.

Once a BroadcastReceiver is listening for messages, there are a few actions that are commonly taken once a push is received:

Creating Dashboard Notifications

By default, Parse will create dashboard notifications based on certain details of the push message that are sent if you specify the «alert» and «title» properties in the notification. In the event that you want to manually manage the notifications, all you have to do is avoid sending the alert or title so parse doesn’t create the notification for you.

Details of setting up custom push notifications can be found in the Notifications guide for a detailed look at creating and managing these notices. See also how to group notifications by modifying existing notices. This is useful if you want to avoid stacking a bunch of notifications and instead group messages or only show the latest one.

When working with push messages, often the notification will launch an activity or the activity may even be launched by the broadcast receiver directly. In these cases, we might want to ensure that the activity launched is the same activity that is already running rather a new instance. To achieve this, we can use launch modes or intent flags such as singleTop to ensure the same activity instance is presented.

Checking App State when Receiving a Broadcast

In certain cases when receiving a push, you want to update an activity only if the activity is on the screen. Otherwise, if the activity is not on screen then you want to create a notification.

There are two approaches to this: either use ActivityManager to check if the activity is running or use ordered broadcasts to override the receiver when the activity is running. Both possible solutions to this are outlined in this post with a code sample here.

We have a full demo of Parse Push sending and receiving which can be found on Github. Check out MyCustomReceiver and MainActivity.

A few quick things to help make implementing push notifications easier:

  • Review the official parse push troubleshooting guide.
  • Make sure to register for the broadcasts using the LocalBroadcastManager with the LocalBroadcastManager.getInstance(this).registerReceiver method.
  • If you need to communicate between a receiver and then a second activity that is not currently in the foreground, you may consider persisting the notification to disk in SQLite. This way we can easily access that from another Activity once that activity switches to the foreground.

Second approach is the more manual way using GCM. Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users’ Android-powered device and also to receive messages from devices on the same connection. Beneath the surface, Parse implements push notifications for Android with GCM.

Read our Google Cloud Messaging guide for specific implementation details.

Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.

Источник

Оцените статью