31

I am using GCM in my application and also using NotificationManager to Create a Notification whenever GCM message is received.Till now everything is working perfectly and GCM message is showing correctly in Notification area, but when I click on the notification it should start an activity of my application which will display the message detail which is not happening. Every-time I click on notification it does not start any activity and it remains as is.My code for creating Notification is :

private void sendNotification(String msg) {
        SharedPreferences prefs = getSharedPreferences(
                DataAccessServer.PREFS_NAME, MODE_PRIVATE);
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, WarningDetails.class);
        Bundle bundle = new Bundle();
        bundle.putString("warning", msg);
        bundle.putInt("warningId", NOTIFICATION_ID);
        intent.putExtras(bundle);
        // The stack builder object will contain an artificial back stack for
        // the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(WarningDetails.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(intent);

        PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.weather_alert_notification)
                .setContentTitle("Weather Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);
        String selectedSound = prefs.getString("selectedSound", "");
        if (!selectedSound.equals("")) {
            Uri alarmSound = Uri.parse(selectedSound);
            mBuilder.setSound(alarmSound);

        } else {
            Uri alarmSound = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
        }

        if (prefs.getBoolean("isVibrateOn", false)) {
            long[] pattern = { 500, 500, 500, 500, 500, 500, 500, 500, 500 };
            mBuilder.setVibrate(pattern);
        }

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

I updated my code to support Preserving Navigation when Starting an Activity just like it happens in Gmail application using the Android developers website since then it stopped working.Someone Please guide me what I am missing or doing wrong in this code.

Ansh
  • 2,366
  • 3
  • 31
  • 51

7 Answers7

48

My problem got solved I just have to add PendingIntent.FLAG_ONE_SHOT flag as well , so I replaced :

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

to

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
                        | PendingIntent.FLAG_ONE_SHOT);
Ansh
  • 2,366
  • 3
  • 31
  • 51
  • @Saty I used it in sendNotification() method which is posted in my question – Ansh Jan 21 '14 at 04:19
  • Hi you used TaskStackBuilder which needs me to require API 16 as minimum need which i dont want to do...is there any alternatives? – Saty Jan 21 '14 at 04:24
  • @Saty TaskStackBuilder is present in android support library which is android.support.v4.app.TaskStackBuilder. So you can use it for API 7 as well by just using support library. – Ansh Jan 21 '14 at 04:51
  • how would i able to find the message in my MainActivity which is in your case is Warning? – Saty Jan 21 '14 at 05:08
  • @Saty what do you mean by find the message in your MainActivity? – Ansh Jan 21 '14 at 07:08
  • if I will set the values in intent how would i be able to retrieve cause my onCreate is not called. – Saty Jan 21 '14 at 07:54
  • Thanks a lot, save me some time! – cwhsu Oct 30 '14 at 05:13
  • this was the solution for me too. But I wonder 1 month it was working without FLAG_ON_SHOT part and just stopped working – supermus Jun 17 '15 at 08:06
  • Thanks! you saved my day! – Wooseong Kim Dec 10 '15 at 12:39
  • Worked for me as well! Superb! – sud007 Sep 13 '16 at 12:27
  • PendingIntent.FLAG_ONE_SHOT will open it once, next time you press notification, it won't do anything. https://developer.android.com/reference/android/app/PendingIntent.html#FLAG_ONE_SHOT – NixSam Nov 16 '17 at 13:10
27

I encountered the same issue and resolved it by adding android:exported="true" to the activity declaration in AndroidManifest.xml.

Tony Vu
  • 4,251
  • 3
  • 31
  • 38
  • this solved my problem too. Before nothing happens. With adding that line into the manifest it works:-) Thanks! – phil Feb 27 '15 at 14:48
  • 2
    Can you please explain why this works? It appears this answer is just a guess. Prove me wrong. – Neon Warge Feb 28 '17 at 05:51
  • Strange! apparently work for me. can you describe it what is the logic behind this? – Radhey Oct 11 '17 at 13:36
  • This worked for me too. The logic behind this (which I believe) is that if the activity has to be called from a different application, you should make it an exported activity. As the notification click is happening outside the app, I think we should declare the activity as exported. Reference https://developer.android.com/guide/topics/manifest/activity-element#exported – rahulrvp Jan 03 '20 at 08:26
2

Here you just passed your Intent into pendingintent: see below

Intent notificationIntent = new Intent(context, Login.class);

 PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
and set this contentintent into your Notification:

Notification noti = new NotificationCompat.Builder(context)
                    .setSmallIcon(icon_small)
                    .setTicker(message)
                    .setLargeIcon(largeIcon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle(title)
                    .setContentText(message)
                    .setContentIntent(**contentIntent**)
                    .setAutoCancel(true).build();

This may help you.

M D
  • 47,665
  • 9
  • 93
  • 114
  • Will this supports Preserving Navigation when Starting an Activity like Gmail application? – Ansh Dec 23 '13 at 13:03
0

if you launch the intended activity using Action String dont forget to add

<intent-filter>
       <action android:name="YOUR ACTION STRING"/>
       <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

inside <activity></activity> tag

Ahmad Muzakki
  • 1,058
  • 12
  • 17
-1

The activity that you want to launch has to be designated as a LAUNCHER activity in your manifest - otherwise it won't launch via a Pending Intent. Add the following to your in the AndroidManifext.xml

<activity
...
android:exported="true">
<intent-filter>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Otherwise you will need to use an Activity that is already designated as a LAUNCHER (such as your MAIN activity)

-2

Do some thing like this on generateNotification() method ..

Replace your activity with Splash.Java class in it.

/**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressWarnings("deprecation")
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        //message = "vivek";
       // Log.d("anjan", message.split("~")[0]);
        //Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);
        Log.d("anjan1", title);
        String text_message = context.getString(R.string.title_activity_main);
        Log.d("anjan1", text_message);

        Intent notificationIntent = new Intent(context, Splash.class);
        // 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, 0);
        notification.setLatestEventInfo(context, title, message, 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);      

    }
AndroidHacker
  • 3,596
  • 1
  • 25
  • 45
  • Your code does not support Preserving Navigation when Starting an Activity – Ansh Dec 23 '13 at 13:02
  • Did you used my code in generateNotification() method. If yes then what error you are getting ? – AndroidHacker Dec 23 '13 at 13:04
  • Problem is it's not preserving the BackStack after starting Activity – Ansh Dec 23 '13 at 13:06
  • Sorry I am not able to get your problem clearly. You mean to say that now on clicking notification activity is started and when we back trace from their then app crashes or some thing like that – AndroidHacker Dec 23 '13 at 13:09
-2

Try this instead of the last line :

mNotificationManager.notify(0, mBuilder.getNotification());

  • But The method getNotification() from the type NotificationCompat.Builder is deprecated – Ansh Dec 23 '13 at 13:00