How to open app in notification in android?

2019-08-05 08:37发布

问题:

In my app, when completing a task in async file, it shows a notification with this code

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent pIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, new Intent(), 0);

    Notification noti = new Notification.Builder(context)
    .setContentTitle("Complete")
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentIntent(pIntent)
    .setAutoCancel(true)
    .build();

    notificationManager.notify(0, noti); 

The problem is when I click the notification, nothing happens. Basically I want it so that, if the app is already open and the user clicks the notification, then nothing should open. If the app is not open (which means its still running but minimized) then I want it to open the app, like maximize it.

Does anyone know how to do this?

Thanks

回答1:

You need an Intent, sample code:

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

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

    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;
    notificationManager.notify(0, notification);

This will open your MainActivity