Android 13 中未显示通知。

huangapple go评论59阅读模式
英文:

Notification not being shown in Android 13

问题

由于Android 13 SDK中通知权限的最新更改,我需要更新我的应用程序以符合通知规则的FCM集成。我已将compileSdk升级到33,targetSdk也升级到33。我编写了代码来请求POST_NOTIFICATIONS权限,提示出现了。点击“允许”后,通知权限已启用。但是在发送推送通知时,应用程序没有收到通知。

我只在请求通知权限时进行了更改,没有在FirebaseMessagingService类中更改任何内容。该应用程序之前的targetSdk版本是30。

英文:

Due to the recent changes in Notification permissions in the Android 13 SDK, I need to update my app with FCM integration to obey the notifications rule. I have upgraded the compileSdk to 33 and also the targetSdk to 33. I have written code to ask POST_NOTIFICATIONS and the prompt appears. On pressing "Allow" the Notification Permission is enabled. But on sending a push notification the app receives no notification.

I only made changes in asking for the notification permission. Did not change anything in FirebaseMessagingService Class. The app was previously targetSdk 30.

class MyFirebaseMessagingService : FirebaseMessagingService() {
var intent: Intent? = null
var badgecount: Int = 0

override fun onMessageReceived(remoteMessage: RemoteMessage) {

    if (remoteMessage.data.isNotEmpty()) {
        try {
            val json = JSONObject(remoteMessage.data.toString())
            handleDataMessage(json)
        } catch (e: Exception) {
            Log.e("FIREBASEEXCEPTION:", e.message.toString())

        }
    }

    if (remoteMessage.notification != null) {
        sendNotification(remoteMessage.notification!!.body)
        println("Message Notification Body:" + remoteMessage.notification!!.body)

    }
    super.onMessageReceived(remoteMessage)
}
private fun handleDataMessage(json: JSONObject) {
    try {
        val data = json.getJSONObject("body")
        val badge = data.getString("badge")
        val message = data.getString("message")
        Log.e("FIREBASE_MSG:", message)
        badgecount = badge.toInt()
        sendNotification(message)
    } catch (e: JSONException) {
        Log.e("JSONEXCEPTION:", e.message.toString())
    } catch (e: java.lang.Exception) {
    }
}
@SuppressLint("ObsoleteSdkInt")
private fun sendNotification(messageBody: String?) {
    ShortcutBadger.applyCount(this, badgecount)
    intent = Intent(this, HomeActivity::class.java)
    intent!!.action = System.currentTimeMillis().toString()
    intent!!.putExtra("Notification_Recieved", 1)
    val notId = NotificationID.getID()
    val stackBuilder = TaskStackBuilder.create(this)
    stackBuilder.addNextIntentWithParentStack(intent!!)
    val pendingIntent = stackBuilder.getPendingIntent(notId, PendingIntent.FLAG_UPDATE_CURRENT)
    val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    val notificationBuilder =
        NotificationCompat.Builder(this)
            .setContentTitle(resources.getString(R.string.app_name))
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
    val notificationManager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel_id = getString(R.string.app_name) + "_01"
        val name: CharSequence = getString(R.string.app_name)
        val importance = NotificationManager.IMPORTANCE_HIGH
        val mChannel = NotificationChannel(channel_id, name, importance)
        notificationBuilder.setChannelId(mChannel.id)
        mChannel.setShowBadge(true)
        mChannel.canShowBadge()
        mChannel.enableLights(true)
        mChannel.lightColor = resources.getColor(R.color.split_bg)
        mChannel.enableVibration(true)
        mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500)
        notificationManager.createNotificationChannel(mChannel)
    }


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notificationBuilder.setSmallIcon(R.drawable.notify_small)
        notificationBuilder.color = resources.getColor(R.color.split_bg)
    } else {
        notificationBuilder.setSmallIcon(R.drawable.nas_large)
        notificationBuilder.color = resources.getColor(R.color.split_bg)
    }

    notificationManager.notify(notId, notificationBuilder.build())

}
}

class MyFirebaseInstanceIDService : FirebaseInstanceIdService() {
    var mContext: Context = this
    override fun onTokenRefresh() {

        //val refreshedToken = FirebaseInstanceId.getInstance().token

        val refreshedToken = FirebaseInstanceId.getInstance().token.toString()

        Log.e("FIREBASETOKEN", refreshedToken)
        sendRegistrationToServer(refreshedToken)
        super.onTokenRefresh()
    }

    private fun sendRegistrationToServer(refreshedToken: String) {
        if (refreshedToken != null) {
            PreferenceManager.setFcmID(mContext, refreshedToken)
        }

    }
}

And in manifest

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<service
            android:name=".fcm.MyFirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".fcm.MyFirebaseInstanceIDService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

答案1

得分: 8

在清单文件上获得权限后,您还需要请求通知运行时权限

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
    if (isGranted) {
        // 可以发布通知。
    } else {
        // 通知用户您的应用程序将不显示通知。
    }
}

private fun askNotificationPermission() {
    // 仅在 API 级别 >= 33(TIRAMISU)时需要
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
            PackageManager.PERMISSION_GRANTED
        ) {
            // 可以发布通知。
        } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
            // 显示一个教育性用户界面,向用户解释授予 POST_NOTIFICATION 权限将启用的功能。
            // 此用户界面应提供用户“确定”和“不感兴趣”按钮。
            // 如果用户选择“确定”,则直接请求权限。
            // 如果用户选择“不感兴趣”,则允许用户在不显示通知的情况下继续。
        } else {
            // 直接请求权限
            requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
        }
    }
}

您还可以检查通知是否已启用或未启用

```kotlin
val notificationManager = getSystemService(NotificationManager::class.java)
val isEnabled = notificationManager.areNotificationsEnabled()

如果您遇到 Manifest.permission.POST_NOTIFICATIONS 权限未解析的问题,请确保导入了以下内容

import android.Manifest
英文:

With the permission on the Manifest file, you also need to ask for Notification Runtime permissions

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
    if (isGranted) {
        // Can post notifications.
    } else {
        // Inform user that that your app will not show notifications.
    }
}

private fun askNotificationPermission() {
    // This is only necessary for API level >= 33 (TIRAMISU)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
            PackageManager.PERMISSION_GRANTED
        ) {
            // Can post notifications.
        } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
            // 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)
        }
    }
}

You can also check if notifications are enabled or not

val notificationManager = getSystemService(NotificationManager::class.java)
val isEnabled = notificationManager.areNotificationsEnabled()

If you faced the problem that is permission Manifest.permission.POST_NOTIFICATIONS not resolved make sure you have this import

import android.Manifest

答案2

得分: 2

目标SDK的使用情况而定。因此,针对Android 13(API级别33),通知默认处于关闭状态。请参考来自Android通知权限文档的以下内容,至少对于新安装的应用程序:

如果用户在运行Android 13或更高版本的设备上安装您的应用程序,您的应用程序的通知默认处于关闭状态。您的应用程序必须等到在请求新的权限并用户授予该权限给您的应用程序之后,才能发送通知。

权限对话框出现的时间基于您的应用程序的目标SDK版本:

如果您的应用程序的目标是Android 13或更高版本,您的应用程序完全控制权限对话框何时显示。利用这个机会向用户解释应用程序为何需要此权限,鼓励他们授予它。

如果您的应用程序的目标是12L(API级别32)或更低版本,系统将在您的应用程序首次启动活动时创建通知通道,或者在您的应用程序启动活动后创建其第一个通知通道时显示权限对话框。通常,这发生在应用程序启动时。

英文:

It depends on the targetSdk in use. So for targeting android 13 (API Level 33) notifications are off by default. See below from the android notification-permission documentation. At least for newly installed apps.

> If a user installs your app on a device that runs Android 13 or higher, your app's notifications are off by default. Your app must wait to send notifications until after you request the new permission and the user grants that permission to your app.
>
> The time at which the permissions dialog appears is based on your app's target SDK version:
>
> If your app targets Android 13 or higher, your app has complete control over when the permission dialog is displayed. Use this opportunity to explain to users why the app needs this permission, encouraging them to grant it.
>
> If your app targets 12L (API level 32) or lower, the system shows the permission dialog the first time your app starts an activity after you create a notification channel, or when your app starts an activity and then creates its first notification channel. This is usually on app startup.

huangapple
  • 本文由 发表于 2023年2月8日 17:19:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定