Unlocking phone and bringing app to foreground

Viewed 108

I have an app that has a background service running that listens for events. One of the events should unlock the phone and bring the app to the foreground.

What approaches here are possible? I was thinking, would it be possible to send a local notification that is actually high priority so it opens the app automatically?

Currently I try to open apps activity this way:

private fun getIntent(pin: String): Intent = Intent(context, XActivity::class.java).apply {
    putExtra(XActivity.EXTRA_SMTH, x)
    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}

private fun showActivity(x: String) {
    val intent = getIntent(x)
    context.startActivity(intent)
}

This code piece works alright if the app is in the foreground, but does not if the app is in the background.

Any ideas/solutions are welcomed.

1 Answers

At first, if you listened for ACTION_SCREEN_ON or ACTION_SCREEN_ON, make sure to explicitly set your listeners ref.

Secondly, due to background restriction, you cannot start an Activity from background. You have to start a foreground service which you will start when the receiver receives the event. From that service, you can launch your activity with your desired intent.

Foreground service needs a notification. Inside your service, create a notification with your intent like following and call startForeground() with this notification. Also create and register NotificationChannel before if not already.

val fullScreenIntent = Intent(this, XActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
    fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)

val notificationBuilder =
        NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Launch Activity")
    .setContentText("Tap to launch Activity")
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setCategory(NotificationCompat.CATEGORY_ALARM) // Set your desired category

    // Use a full-screen intent only for the highest-priority alerts where you
    // have an associated activity that you would like to launch after the user
    // interacts with the notification. Also, if your app targets Android 10
    // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
    // order for the platform to invoke this notification.
    .setFullScreenIntent(fullScreenPendingIntent, true)

val alarmNotification = notificationBuilder.build()
Related