在启动某些活动之前,小部件无法在 Android 11 上的设备启动时启动服务 [英] Widget can't start a service on device boot on Android 11 until some activity is launched

查看:40
本文介绍了在启动某些活动之前,小部件无法在 Android 11 上的设备启动时启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val startServiceIntent = TestService.getServiceIntent(context).let {
    PendingIntent.getService(context, 0, it, PendingIntent.FLAG_UPDATE_CURRENT)
}
val views = RemoteViews(context.packageName, R.layout.layout_app_widget).apply {
    setOnClickPendingIntent(R.id.start_service_btn, startServiceIntent) // doesn't work on boot device
    setOnClickPendingIntent(R.id.start_activity_btn, startActivityIntent) // works fine
}
appWidgetManager.updateAppWidget(appWidgetId, views)

如何对待这种行为?我如何至少向用户显示一条消息,即在他启动应用程序(使其可见)或在此设备会话期间启动活动之前,无法从小部件启动服务?

How to treat such behaviour? How can I at least show a message to a user that a service can't be started from widget until he launches the app (make it visible) or launch an activity instead during this device session?

因为现在我按下按钮启动服务时没有任何反应,直到我至少启动一次应用程序

Because now nothing happens when I press the button to start the service until I launch the app at least once

Android 11 上是否有任何方法可以检查我们是否可以从后台/小部件启动前台服务、相机等?如何确定用户在设备的当前会话中至少启动了一次应用的 Activity?

Is there any method on Android 11 to check if we can start foreground service, camera and so on from background / widget? How to find out that user has launched an activity of app at least once for the current session of the device?

推荐答案

基于@CommonsWare 注释,我需要使用 PendingIntent.getForegroundService() 而不是 PendingIntent.getService()代码>

Based on @CommonsWare comment I need to use PendingIntent.getForegroundService() instead of PendingIntent.getService()

这篇关于在启动某些活动之前,小部件无法在 Android 11 上的设备启动时启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆