我正在开发一个 Android 应用程序,我面临着一个似乎与 Android 14(API 级别 34)相关的问题。在第一次应用程序启动期间,我将提出通知权限请求 (POST_NOTIFICATIONS)。但是,当触发此请求并且用户与其交互(允许或拒绝它)时,我的应用程序似乎挂在启动它上。如果我将应用程序置于后台并返回,则会出现登录页面。
这是我的相关代码:
if (isFirstRun) {
setupPushNotificationsChannel()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// Check notifications permission
if (ContextCompat.checkSelfPermission(
this@LoginActivity,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_DENIED
) {
requestPermissions(
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
REQUEST_POST_NOTIFICATION_CODE_PERMISSION
)
}
}
// Flip firstRun
preferences.edit().putBoolean(FIRST_RUN_KEY, false).apply()
}
private fun setupPushNotificationsChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
val channelId = getString(R.string.default_notification_channel_id)
val channelName = getString(R.string.default_notification_channel_name)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannel(
NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH
)
)
}
}
重写有趣的 onRequestPermissionsResult() 以添加逻辑以根据用户交互导航到登录屏幕。
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == REQUEST_POST_NOTIFICATION_CODE_PERMISSION && grantResults == PackageManager.PERMISSION_GRANTED)
// Load login page
}