Search code examples
javaandroidalarmmanager

When a notification's clicked, open an activity


My code:

public class OnAlarmReceive extends BroadcastReceiver {

      @Override
      public void onReceive(Context context, Intent intent) 
      {
          CharSequence title = "Hello";
          CharSequence message = "la!";
          NotificationManager notificationManager;
          notificationManager = (NotificationManager) context.getSystemService("notification");
          Notification notification;
          notification = new Notification(com.example.pack.R.drawable.ic_launcher, "test", System.currentTimeMillis());

          PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, null, 0);

          notification.setLatestEventInfo(context, title, message, pendingIntent);
          notificationManager.notify(1010, notification);

      }
}

I use alarmmanager for receive, how can I open an activity when user clicks on notification?


Solution

  • You need to change your declaration of the PendingIntent:

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, null, 0);
    

    With something like this that would describe the intent to start the activity you want to launch (change the 3rd argument accordingly)

    PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), new Intent(this, YourAppClass.class), 0);