Android push notification: Get data, store and display on new activity on click of notification

65,778

Solution 1

I solved the issues as:

  1. Send JSON data via push notification. A. Able to send the data from SERVER with the help of PHP JSON service of size 4kb.

  2. Save the data into SQLite database. A. Saved the data in SQLite when data comes from push notification in onMessage()

    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("price");
        Log.d("OnMSG",message);
    
        displayMessage(context, message);
    
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
        dataBaseHelper.openDataBase();
        dataBaseHelper.insertData(message);
        dataBaseHelper.close();
    
        // notifies user
        generateNotification (context, message);
    }
    
  3. Open new activity on click of push notification. A. I done this using pending intent in generate notification function called from onMessage().

    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
    
        String title = context.getString(R.string.app_name);
    
        Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.putExtra("ms", message);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
        notification.defaults |= Notification.DEFAULT_SOUND;
    
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);     
    }
    
  4. Display data coming from push notification of new activity. A. This achieves as when new activity invokes on click of notification (from above point 3 code) I get data from SQLite in main activity onCreate().

    DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
    dataBaseHelper.openDataBase();
    Cursor c = dataBaseHelper.getData();
    String data = null;
    if(c.getCount()>0){
        if(c.moveToFirst()){
            do{
            data = c.getString(0);
        } while(c.moveToNext());
        }
    } else {
        data = "No Data";
    }
    
  5. If the application is closed so after click on notification the app get started. A. This task is achieved from point no 3.

Solution 2

GCMIntentService.java

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;
/**
 * IntentService responsible for handling GCM messages.
 */
public class GCMIntentService extends GCMBaseIntentService {

    @SuppressWarnings("hiding")
    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context,"onregisterd");
        ServerUtilities.register(context, registrationId);
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, "GCM unregistered");
        if (GCMRegistrar.isRegisteredOnServer(context)) {
            ServerUtilities.unregister(context, registrationId);
        } else {
            // This callback results from the call to unregister made on
            // ServerUtilities when the registration to the server failed.
            Log.i(TAG, "Ignoring unregister callback");
        }
    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message =intent.getExtras().getString("message");
        displayMessage(context, message);
        // notifies user
        generateNotification(context,message );
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = ("total deleted"+ total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, ("error:"+ errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, ("Recover error:"+ errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.icon;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, "Dear Customer , New Product has been Launched", when);
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        notification.sound=soundUri;
        String title = context.getString(R.string.app_name);
        Intent notificationIntent = new Intent(context, lap_gcm.class);
        notificationIntent.putExtra("message", message);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    }

}

Result Activity

lap_gcm.java

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class lap_gcm extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        String message=getIntent().getStringExtra("message");
        //Here is Your message

        }
    }

This code base on the blog you mention i used in one of my application i develop. This will show notification on new notification receive and open a new activity when the user clicked the notification.

Always send don't send all data through push notification. u just send some small message like data then pull the data from the server, once the message received in your device, then store it in db.

Solution 3

Send JSON data via push notification

You can send the JSON as data in the notification message from your server side code. Once you get the notification then you would receive a JSON in the message where you can do whatever you want.

Save the data into SQLite database

This is simple as per your requirement, you can insert the data whatever received in the JSON. You can get the data from the JSON after parsing.

Open new activity on click of push notification.

You can do like below

mNotificationManager = (NotificationManager)
        this.getSystemService(Context.NOTIFICATION_SERVICE);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        new Intent(this, YourActivity.class), 0);

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);

mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

Display data coming from push notification of new activity.

You can display the data whatever receive from push message but you have to parse the JSON.

If the application is closed so after click on notification the app get started.

My above code will work for you in this case also.

See here for JSON parsing : http://www.vogella.com/tutorials/AndroidJSON/article.html

All in all, you have to add the data in the JSON form in your server cod that you would get when you push the GCM from the server and later perform parse the JSON and do whatever you want.

Share:
65,778
Manoj Fegde
Author by

Manoj Fegde

Android Developer 7+ year experience.

Updated on March 30, 2020

Comments

  • Manoj Fegde
    Manoj Fegde about 4 years

    I am developing an application which is having push notification functionality. I followed the following link as Android Push Notification

    I tried and successfully send URL and open the web page on click of notification by doing the following change in code of generateNotification().

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, "Message received", System.currentTimeMillis());
        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
        //adding LED lights to notification
        notification.defaults |= Notification.DEFAULT_LIGHTS;
    
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(message));
        //startActivity(browserIntent);
    
        //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        notification.setLatestEventInfo(context, "Message", "New message received", pendingIntent);
        notificationManager.notify(0, notification);
    

    I am able to send the data with the help of push notification from the server. Now i want to perform following tasks:

    1. Send JSON data via push notification.

    2. Save the data into SQLite database.

    3. Open new activity on click of push notification.

    4. Display data coming from push notification of new activity.

    5. If the application is closed so after click on notification the app get started.

    So please guide me what steps should i follow to perform the above task.

  • Manoj Fegde
    Manoj Fegde about 10 years
    Can you please give me the steps how to display data of push notification on new activity on click of notification when the app is not running.
  • CoolMonster
    CoolMonster about 10 years
    Intent notificationIntent = new Intent(context, lap_gcm.class); notificationIntent.putExtra("message", message); in generateNotification see this i sent the message through intent to activity
  • Manoj Fegde
    Manoj Fegde about 10 years
    I followed the same but on click of notification data is not displaying.
  • CoolMonster
    CoolMonster about 10 years
    did u created lap_gcm activity. U have to launch your activity
  • TapanHP
    TapanHP about 6 years
    new NotificationCompat.Builder(this); is deprecated in Android Oreo, Please check docs and use Notification Channel implementation.