Search code examples
androidandroid-notificationsandroid-pendingintent

Android Notification Action: pending Intent not working


I'm having issues with Android Notification's Actions. Here's my idea: My BroadcastReceiver wakes up upon a broadcast, then it creates a notification. This notification should:

  • open MainActivity when tapping its body
  • share a message when tapping the button "Condividi"

I managed to get the ACTION_SEND working when tapping the notification, but i had no luck for the action...

Couldn't find anything on the web, only pendingIntents that open activities.

Here's my code:

public class AlarmReceiver extends BroadcastReceiver {
static int notificationId = 0;
@Override
public void onReceive(Context context, Intent intent) {
    Log.d("AlarmReceiver","ricevuto " + intent.getAction());
    Calendar calendar = Calendar.getInstance();
    String tipo = "sconosciuto";
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setSmallIcon(R.drawable.ic_flag_black_24dp);
    if(intent.getAction().equals(Constants.ALARM_ACTION_PALINDROM)){
        tipo="palindromo";
    }
    if(intent.getAction().equals(Constants.ALARM_ACTION_DOUBLE)){
        tipo="simmetrico";
    }

    mBuilder.setContentTitle("Orario " + tipo + "!");

    String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
    mBuilder.setContentText(currentTime);

    Intent shareIntent = new Intent();

    Intent notifIntent = new Intent(context,MainActivity.class);
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT,"Sono le " + currentTime +", " + tipo + "\u2764");
    Intent shareIntentWithChooser = Intent.createChooser(shareIntent,"Send to");

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(notifIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pendingIntentShare = PendingIntent.getBroadcast(context,notificationId,shareIntentWithChooser,PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.addAction(R.drawable.ic_send_black_18dp,"Condividi",pendingIntentShare);

    mBuilder.setContentIntent(pendingIntent);
    Notification notification = mBuilder.build();
    notification.flags = Notification.DEFAULT_LIGHTS|Notification.FLAG_AUTO_CANCEL;

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId,notification);
    notificationId++;
}

}

Thanks in advance, i really can't wrap my mind around it!


Solution

  • You should use getActivity() instead of getBroadcast() to create your PendingIntent, since you want to start an Activity with ACTION_SHARE and not send a broadcast.