android - 解锁手机并将应用程序置于前台
问题描述
我有一个应用程序运行着一个后台服务来监听事件。其中一个事件应该解锁手机并将应用程序带到前台。
这里有哪些可能的方法?我在想,是否可以发送一个实际上具有高优先级的本地通知,以便它自动打开应用程序?
目前我尝试以这种方式打开应用程序活动:
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)
}
如果应用程序在前台,这段代码可以正常工作,但如果应用程序在后台,则不能。
欢迎任何想法/解决方案。
解决方案
一开始,如果你听了ACTION_SCREEN_ON
or 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()
推荐阅读
- java - 为什么邮递员显示404未找到
- java - 无论如何,使用 getFrom 和 getTo 忽略 PlayerMoveEvent 中的某个坐标轴
- python - 如何使用 PyTorch 构建具有 400 个节点隐藏层的 CNN?
- django - Django 上 Count 函数的不同行为
- javascript - 如何使复选框的文本也切换
- arduino - 如何从磁力计、加速度计和陀螺仪获得准确的航向
- android - 如何在 Room 数据库中调用更改来更新 UI?
- python - 我想使用带有变量的 wget 作为参数
- haskell - 这个简单的 do notation desugar 是为了什么?
- python - 为什么我们需要'for循环'的变量?