Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on GCM notification not opening desired Activity in Android Kitkat

I am doing an app which requires me send push notification to my users.

I am using this example. First I had issue clicking on notification on notification bar which was not opening desired Activity however that is been solved now. I am getting notification while app active or in background.

However one of my phone (Nexus 4 which has Android Kitkat 4.4) is behaving unexpectedly: it displays notification through broadcast when app is in foreground and displays message, but does not start the Activity which needs to be start when click on notification on notification bar.Sometimes it does not receive the notifications as well where as my other phones does.

package com.androidhive.pushnotifications;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast; 
import com.google.android.gcm.GCMBaseIntentService;

import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
import static com.androidhive.pushnotifications.CommonUtilities.displayMessage;
import android.database.sqlite.SQLiteDatabase;

public class GCMIntentService extends GCMBaseIntentService {
private static SQLiteDatabase sampleDB;
private static final String SAMPLE_DB_NAME = "pushData.db";
private static final String SAMPLE_TABLE_NAME = "pushtabledata";
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
    super(SENDER_ID);

}

/**
 * Method called on device registered
 **/
@Override
protected void onRegistered(Context context, String registrationId) {
    Log.i(TAG, "Device registered: regId = " + registrationId);
    displayMessage(context, "Your device registred with GCM");
    Log.d("NAME", MainActivity.name);
    ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
}

/**
 * Method called on device un registred
 * */
@Override
protected void onUnregistered(Context context, String registrationId) {
    Log.i(TAG, "Device unregistered");
    displayMessage(context, getString(R.string.gcm_unregistered));
    ServerUtilities.unregister(context, registrationId);
}

/**
 * Method called on Receiving a new message
 * */


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

/**
 * Method called on receiving a deleted message
 * */
@Override
protected void onDeletedMessages(Context context, int total) {
    Log.i(TAG, "Received deleted messages notification");
    String message = getString(R.string.gcm_deleted, total);
    displayMessage(context, message);
    // notifies user
    generateNotification(context, message);
}

/**
 * Method called on Error
 * */
@Override
public void onError(Context context, String errorId) {
    Log.i(TAG, "Received error: " + errorId);
    displayMessage(context, getString(R.string.gcm_error, errorId));
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
    // log message
    Log.i(TAG, "Received recoverable error: " + errorId);
    displayMessage(context, getString(R.string.gcm_recoverable_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) {     
    /*NotificationManager  mNotificationManager = (NotificationManager)
              context.getSystemService(Context.NOTIFICATION_SERVICE);

      Intent inty = new Intent(context, MainActivity.class);
      inty.putExtra("message", message);
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
              inty, PendingIntent.FLAG_UPDATE_CURRENT);

      NotificationCompat.Builder mBuilder =
              new NotificationCompat.Builder(context)
      .setSmallIcon(R.drawable.ic_launcher)
      .setContentTitle("GCM Notification")
      .setStyle(new NotificationCompat.BigTextStyle()
      .bigText(message))
      .setContentText(message);

      mBuilder.setContentIntent(contentIntent);
      mNotificationManager.notify(0, mBuilder.build());*/
    // Log.d("in GCM Intent", message);
     int icon = R.drawable.ic_launcher;
     long when = System.currentTimeMillis();
     NotificationManager notificationManager = (NotificationManager)
             context.getSystemService(Context.NOTIFICATION_SERVICE);
     Notification notification = new Notification();
     StringBuffer sb = new StringBuffer();
     if(message != null){
        Log.d("in GCM Intent", "not null");
     if(message.contains("@@@@@@@@@@@@"))
     {

         Log.d("in GCM Intent", "got  @");
         String []parts = message.split("@@@@@@@@@@@@");

         Log.d("After : separate", parts[0] + "" + parts[1]);
         sb.append(parts[0]);
         sampleDB= context.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
         ContentValues values = new ContentValues();
         values.put("title", parts[0]);
         DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
         String date = df.format(Calendar.getInstance().getTime());
         values.put("time", date);
         values.put("message", parts[1]);   
         try{
         sampleDB.beginTransaction();
         sampleDB.insert(SAMPLE_TABLE_NAME, null, values); 
         sampleDB.setTransactionSuccessful();

         }
         catch(Exception e)
         {
             Log.d("Exception",e.toString());
         }
         finally{
             sampleDB.endTransaction();
         }
         sampleDB.close();
     }
     else
     {
         sb.append(message);
     }
     }
     else
     {
         sb.append("No data");
     }
     String title = context.getString(R.string.app_name);
      notification.when = when;
      notification.icon = icon;
     Intent notificationIntent = new Intent(context, MainActivity.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_UPDATE_CURRENT);
     notification.setLatestEventInfo(context, title, sb.toString(), intent);
     notification.flags |= Notification.FLAG_AUTO_CANCEL;

     // Play default notification sound
     notification.defaults |= Notification.DEFAULT_SOUND;

     // Vibrate if vibrate is enabled
     notification.defaults |= Notification.DEFAULT_VIBRATE;
     notificationManager.notify(0, notification);  
}

}

I tried to Google about this issue and found some data like following, however it does not make any sense.

link1

link2

link3

Edited:- I have pasted the code of GCMIntentService as asked.

like image 473
Saty Avatar asked Jan 24 '14 10:01

Saty


2 Answers

This issue is known for Android Kitkat 4.4 and Lollipop. Please add :

android:exported="true"

in android manifest inside activity tag which is supposed to be opened after tapping notification from status bar.

Also now as Google Play Services has been updated so import Google Play Services Library into your project instead importing gcm.jar.

like image 139
satyapol Avatar answered Nov 04 '22 09:11

satyapol


I was experiencing the same problem. Try to use

PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);` 

intstead of

PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
like image 27
amukhachov Avatar answered Nov 04 '22 09:11

amukhachov