如何请求权限发送通知Android?

db2dz4w8  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(240)

启动具有通知权限的应用程序时,如何创建弹出窗口?在Android 13中,这是强制性的。权限已在清单中。我需要以某种方式嵌入到这个代码的权限请求,我不知道如何做到这一点。请帮助这是我的类与通知:

class NotificationReceiver : BroadcastReceiver() {
    private val TAG = "Notifi"
    private var cityName: String = ""
    private var location: String = ""

    override fun onReceive(context: Context, intent: Intent) {
        cityName = intent.getStringExtra("CITY_KEY").toString()
        location = intent.getStringExtra("LOCATION_KEY").toString()
        sendNotification(context)
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("MissingPermission")
    private fun sendNotification(context: Context) {
        val mainActivityIntent = Intent(context, MainActivity::class.java)
        mainActivityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent, PendingIntent.FLAG_IMMUTABLE)
        // Создайте канал уведомления для Android Oreo и выше
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "NotificationChannelName"
            val descriptionText = "NotificationChannelDescription"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel("CHANNEL_ID", name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            Log.d(TAG, "Step 1")
        }

        val expandedView = RemoteViews(context.packageName, R.layout.notification_expanded)

        Log.d(TAG, "Сообщение отправилось")

        GlobalScope.launch(Dispatchers.Main) {
            try {
                val dataForNotifi = withContext(Dispatchers.IO) {
                    fetchWeatherData(0, cityName, location)
                }

                val collapsedView = RemoteViews(context.packageName, R.layout.custom_collapsed_notification)
                collapsedView.setTextViewText(R.id.notification_text1, dataForNotifi.pushCurrentTemp)
                collapsedView.setTextViewText(R.id.notification_text2, dataForNotifi.pushMaxMin)
                // Установите ресурсы изображений для ImageView
                collapsedView.setImageViewResource(R.id.notification_icon, R.drawable.ic_app_push)
                collapsedView.setImageViewResource(R.id.notification_icon2, dataForNotifi.pushCurrentImage)

                // Создайте уведомление
                val builder = NotificationCompat.Builder(context, "CHANNEL_ID")
                    .setSmallIcon(R.drawable.ic_app_push)
                    .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                    .setCustomContentView(collapsedView)
                    .setCustomBigContentView(expandedView)
                    .setContentIntent(pendingIntent) // <- добавьте PendingIntent к сборщику уведомлений (NotificationCompat.Builder)
                    .setAutoCancel(true) // <- это остановит уведомление после нажатия на него

                val notificationManagerCompat = NotificationManagerCompat.from(context)
                notificationManagerCompat.notify(1, builder.build())

                val currentTime = Calendar.getInstance().timeInMillis
                val dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())
                val timeFormatted = dateFormat.format(currentTime)

                expandedView.setTextViewText(R.id.push_address, dataForNotifi.pushAddress)
                expandedView.setTextViewText(R.id.push_time, timeFormatted)
                expandedView.setImageViewResource(R.id.push_current_image, dataForNotifi.pushCurrentImage)
                expandedView.setTextViewText(R.id.push_current_temp, dataForNotifi.pushCurrentTemp)

                expandedView.setTextViewText(R.id.push_firstcase_day, dataForNotifi.pushFirstCaseDay)
                expandedView.setImageViewResource(R.id.push_firstcase_image, dataForNotifi.pushFirstCaseImage)
                expandedView.setTextViewText(R.id.push_firstcase_temp, dataForNotifi.pushFirstCaseTemp)

                expandedView.setTextViewText(R.id.push_secondcase_day, dataForNotifi.pushSecondCaseDay)
                expandedView.setImageViewResource(R.id.push_secondcase_image, dataForNotifi.pushSecondCaseImage)
                expandedView.setTextViewText(R.id.push_secondcase_temp, dataForNotifi.pushSecondCaseTemp)

                expandedView.setTextViewText(R.id.push_thirdcase_day, dataForNotifi.pushThirdCaseDay)
                expandedView.setImageViewResource(R.id.push_thirdcase_image, dataForNotifi.pushThirdCaseImage)
                expandedView.setTextViewText(R.id.push_thirdcase_temp, dataForNotifi.pushThirdCaseTemp)

                expandedView.setTextViewText(R.id.push_fourthcase_day, dataForNotifi.pushFourthCaseDay)
                expandedView.setImageViewResource(R.id.push_fourthcase_image, dataForNotifi.pushFourthCaseImage)
                expandedView.setTextViewText(R.id.push_fourthcase_temp, dataForNotifi.pushFourthCaseTemp)

                // Обновите уведомление
                notificationManagerCompat.notify(1, builder.build())

                Log.d(TAG, "Сообщение обновилось")
            } catch (e: Exception) {
                // Обработка ошибок
                Log.e(TAG, "Error: ${e.message}", e)
            }
        }
    }

    suspend fun fetchWeatherData(position: Int, cityName: String, userLocation: String): DataForNotifi {
        val weather = Weather()
        return suspendCancellableCoroutine { continuation ->
            weather.getWeatherData(position, cityName, userLocation) { _, _, _, dataForNotifi ->
                continuation.resume(dataForNotifi)
            }
        }
    }
}

下面是活动中的代码:

private fun setupNotificationAlarm() {
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, NotificationReceiver::class.java)

        intent.putExtra("CITY_KEY", city)
        intent.putExtra("LOCATION_KEY", coordinates)
        
        val pendingIntent = PendingIntent.getBroadcast(
            this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE
        )
        
        val intervalInMillis = TimeUnit.MINUTES.toMillis(1)

        alarmManager.setExact(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + intervalInMillis,
            pendingIntent
        )
    }

    private fun requestExactAlarmPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

            if (!alarmManager.canScheduleExactAlarms()) {
                val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {data = Uri.fromParts("package", packageName, null)
                }
                val requestCode = 0
                startActivityForResult(intent, requestCode)
            }
        }
    }
eh57zj3b

eh57zj3b1#

在Android 13中,您必须手动请求通知权限。首先检查构建版本,如果构建版本低于13,则不需要请求权限,否则使用以下代码:

if (SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
            PackageManager.PERMISSION_GRANTED
        ) {
           // Do your task on permission granted
        } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
            // TODO: display an educational UI explaining to the user the features that will be enabled
            //       by them granting the POST_NOTIFICATION permission. This UI should provide the user
            //       "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission.
            //       If the user selects "No thanks," allow the user to continue without notifications.
        } else {
            // Directly ask for the permission
            requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        }
    }
    else{
        // Below Android 13 You don't need to ask for notification permission.
    }

像这样创建权限活动结果方法,以便您可以获得所请求的权限是否被授予。

private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission(),
) { isGranted: Boolean ->
    if (isGranted) {
        // Permission Granted
    } else {
        // Permission Denied / Cancel
    }
}

相关问题