Search code examples
androidandroid-intentpush-notificationandroid-pendingintent

Open from notification gives NullException


I'm trying to open my app from a notification push. But I have a problem, I have 3 activities, the activity which works as launcher, and 2 others.

When I click on a push if I do:

new Intent(this, ClientActivity.class) the app opens in the activity that was working previously. Is the same if the app was in foreground or background.

The problem is when I click on a notification and the app is killed, the ClientActivity is not loaded, so the app produces a Runtime Exception because ClientActivity was there.

How I can know what Activity is running currently?

Intent intent = new Intent(this, activityToOpen);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
if(pushTypeSecureSignature){
    intent.putExtra("PUSH_TYPE_SECURE_SIGNATURE", true);
}
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 0);

Solution

  • If you want a click on the Notification to just bring your app to the foreground in whatever state it was in when it went to the background, then just use this:

    Intent = PackageManager.getLaunchIntentForPackage("my.app.package.name")
    

    Now wrap this Intent in a PendingIntent and put it in your Notification.

    This will bring your app to the foreground (if it is running) in whatever state it was in. If your app is not running, this will just launch the root Activity of your app (the same thing that happens when the user taps the app icon on the HOME screen).