0

Similar questions 1

Similar question 2

TL;DR: Answers to How to perform notification-action (click) on lock-screen? don't work anymore cuz now you can't startActivity() from services or broadcast receivers. Any suggestions on how to achieve this?

DETAILS

I have an app that must open an activity on top of the lock screen. Before targeting Android 12, I could just add an action button to the notification:

val intent = Intent(this, NotificationReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, flags)
val builder = NotificationCompat.Builder(context, channelId)
builder.addAction(drawable, buttonText, pendingIntent)

pendingIntent.getBroadcast() worked great on the notification action button, because the broadcast will be fired even if the device is unlocked.

The NotificationReceiver class would then get the broadcast WITHOUT unlocking the phone, and it would open the activity on top of the lock screen from there.

Android 12 introduced Notification Trampoline restrictions, now we cannot call startActivity() from broadcast receivers or services. I could use pendingIntent.getActivity instead of pendingIntent.getBroadcast and launch the Activity directly, but the problem is that getActivity isn't triggered until AFTER the phone is unlocked (you click on the notification action button > it requests to unlock device > once unlocked, it starts the activity)

Any idea on how to open an activity from a notification without unlocking your phone targeting Android 12+?

1 Answers1

0

If I understood you right, I have something similar. Im my app I have an alarm which should open the alarm activity when alarm triggered. What I did to solve this problem:

1) Use full screen intents:

When you configure your notification, just add this line to tell that you are going to use full screen intent:

val pendingIntent = //Pending intent of the activity to launch
.setFullScreenIntent(pendingIntent)

2) Use flag on your activity:

To tell the system that your activity is going to appear above the lock screen, in your onCreate() before you call super set this flags:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

Tested on Android 12. Activity is launching

Dmitriy Mitiai
  • 1,112
  • 12
  • 15