and*_*per 10 android alarmmanager
Android Q 似乎有很多新的限制,但警报不应该是其中之一:
https://developer.android.com/guide/components/activities/background-starts
看来我为设置闹钟而编写的旧代码在 P 上运行良好,但不能再正常工作了:
主活动.kt
class MainActivity : AppCompatActivity() {
private lateinit var manager: AlarmManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
button.setOnClickListener {
Log.d("AppLog", "alarm set")
Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show()
val timeToTrigger = System.currentTimeMillis() + 10 * 1000
setAlarm(this, timeToTrigger, 1)
}
}
companion object {
fun setAlarm(context: Context, timeToTrigger: Long, requestId: Int) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
when {
VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP -> manager.setAlarmClock(AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
VERSION.SDK_INT >= VERSION_CODES.KITKAT -> manager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
else -> manager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
接收者确实获得了 Intent,但是当它尝试打开 Activity 时,有时什么也没有发生:
报警接收器.kt
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("AppLog", "AlarmReceiver onReceive")
context.startActivity(Intent(context, Main2Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
Run Code Online (Sandbox Code Playgroud)
将此视为错误,我在这里报告(包括示例代码)
我试图找到 Q 上的新内容,看看是什么原因导致的,但我找不到。
我还尝试(如果您查看代码)直接打开 Activity 而不是通过 BroadcastReceiver。
而且,我尝试将 BroadcastReceiver 设置为在不同的进程上运行。
所有这些都没有帮助。
我发现虽然一些闹钟应用程序无法正常工作(例如Timely),但有些应用程序工作正常(例如“ Alarm Clock Xtreme ”)。
在 Android Q 上,是否有官方方法可以让闹钟正常工作?要打开一个将显示给用户的 Activity,就像闹钟应用程序应该做的那样?
我编写的代码有什么问题?为什么它在 P 上有效,但在 Q 上不总是有效?
编辑:在被建议在我启动 Activity 时显示通知并使用 FullScreenIntent 之后,我得到了一些工作,但它仅在屏幕关闭时才有效。当屏幕打开时,它只显示通知,这是一件坏事,因为重点是向用户显示警报,而一些用户(如我)不想抬头-警报通知,在某事中间弹出而不暂停任何事情。我希望有人可以帮助解决这个问题,因为这曾经是一件很容易做的事情,现在它变得太复杂了......
这是当前代码(可在此处获得):
通知 ID
object NotificationId {
const val ALARM_TRIGGERED = 1
@JvmStatic
private var hasInitialized = false
@UiThread
@JvmStatic
fun initNotificationsChannels(context: Context) {
if (hasInitialized || Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return
hasInitialized = true
val channelsToUpdateOrAdd = HashMap<String, NotificationChannel>()
val channel = NotificationChannel(context.getString(R.string.channel_id__alarm_triggered), context.getString(R.string.channel_name__alarm_triggered), NotificationManager.IMPORTANCE_HIGH)
channel.description = context.getString(R.string.channel_description__alarm_triggered)
channel.enableLights(true)
channel.setSound(null, null)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channel.enableVibration(false)
channel.setShowBadge(false)
channelsToUpdateOrAdd[channel.id] = channel
//
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val existingChannels = notificationManager.notificationChannels
if (existingChannels != null)
for (existingChannel in existingChannels) {
// The importance of an existing channel will only be changed if the new importance is lower than the current value and the user has not altered any settings on this channel.
// The group an existing channel will only be changed if the channel does not already belong to a group. All other fields are ignored for channels that already exist.
val channelToUpdateOrAdd = channelsToUpdateOrAdd[existingChannel.id]
if (channelToUpdateOrAdd == null) //|| channelToUpdateOrAdd.importance > existingChannel.importance || (existingChannel.group != null && channelToUpdateOrAdd.group != existingChannel.group))
notificationManager.deleteNotificationChannel(existingChannel.id)
}
for (notificationChannel in channelsToUpdateOrAdd.values) {
notificationManager.createNotificationChannel(notificationChannel)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务.kt
class MyService : Service() {
override fun onBind(p0: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("AppLog", "MyService onStartCommand")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationId.initNotificationsChannels(this)
val builder = NotificationCompat.Builder(this, getString(R.string.channel_id__alarm_triggered)).setSmallIcon(android.R.drawable.sym_def_app_icon) //
.setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
builder.setShowWhen(false)
builder.setContentText("Alarm is triggered!")
builder.setContentTitle("Alarm!!!")
val fullScreenIntent = Intent(this, Main2Activity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setFullScreenIntent(fullScreenPendingIntent, true)
startForeground(NotificationId.ALARM_TRIGGERED, builder.build())
startActivity(Intent(this, Main2Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
Handler().postDelayed({
stopForeground(true)
stopSelf()
}, 2000L)
} else {
startActivity(Intent(this, Main2Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
return super.onStartCommand(intent, flags, startId)
}
}
Run Code Online (Sandbox Code Playgroud)
主活动.kt
class MainActivity : AppCompatActivity() {
private lateinit var manager: AlarmManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
button.setOnClickListener {
Log.d("AppLog", "alarm set")
Toast.makeText(this, "alarm set", Toast.LENGTH_SHORT).show()
val timeToTrigger = System.currentTimeMillis() + 10 * 1000
setAlarm(this, timeToTrigger, 1)
}
}
companion object {
fun setAlarm(context: Context, timeToTrigger: Long, requestId: Int) {
val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
// val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, Main2Activity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
// val pendingIntent = PendingIntent.getService(context, requestId, Intent(context, MyService::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
when {
VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP -> manager.setAlarmClock(AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
VERSION.SDK_INT >= VERSION_CODES.KITKAT -> manager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
else -> manager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
报警接收器.kt
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("AppLog", "AlarmReceiver onReceive")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, MyService::class.java))
} else context.startService(Intent(context, MyService::class.java))
}
}
Run Code Online (Sandbox Code Playgroud)
Com*_*are 10
我编写的代码有什么问题?为什么它在 P 上有效,但在 Q 上不总是有效?
您正在尝试从后台启动活动。这在大多数情况下在 Android 10+ 上是被禁止的。
根据文档,警报不应受到伤害。
从您引用的材料中,重点补充说:“应用程序收到来自系统的通知PendingIntent”。您没有使用通知。因此,此例外不适用。
在 Android Q 上,是否有官方方法可以让闹钟正常工作?要打开一个将显示给用户的 Activity,就像闹钟应用程序应该做的那样?
使用全屏通知Intent,如文档中所述。如果屏幕被锁定,则在发出通知时将显示您的活动。如果屏幕已解锁,则会显示高优先级(“抬头”)通知。换句话说:
如果设备没有被使用,你会得到你想要的
如果设备可能正在被使用,用户无需您接管屏幕即可了解事件,因此您不会干扰用户正在做的任何事情(例如,在驾驶时依赖导航应用程序)
| 归档时间: |
|
| 查看次数: |
4598 次 |
| 最近记录: |