首页 > 解决方案 > 解锁手机并将应用程序置于前台

问题描述

我有一个应用程序运行着一个后台服务来监听事件。其中一个事件应该解锁手机并将应用程序带到前台。

这里有哪些可能的方法?我在想,是否可以发送一个实际上具有高优先级的本地通知,以便它自动打开应用程序?

目前我尝试以这种方式打开应用程序活动:

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)
}

如果应用程序在前台,这段代码可以正常工作,但如果应用程序在后台,则不能。

欢迎任何想法/解决方案。

标签: android

解决方案


一开始,如果你听了ACTION_SCREEN_ONor ACTION_SCREEN_ON,请确保明确设置你的听众ref

其次,由于后台限制,您无法从后台启动 Activity。您必须启动一个前台服务,当接收者收到事件时您将启动该服务。通过该服务,您可以按照您想要的意图启动您的活动。

前台服务需要通知。在您的服务中,根据您的意图创建一个通知,例如关注并startForeground()使用此通知进行调用。如果还没有,也可以在之前创建和注册 NotificationChannel。

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()

推荐阅读