gpt4 book ai didi

java - android:根据FCM通知的数据采取行动

转载 作者:行者123 更新时间:2023-12-02 02:08:07 24 4
gpt4 key购买 nike

我正在开发一个使用 firebase 云消息传递来接收通知的 Android 应用程序,我将通知和数据从 fcm 发送到我的应用程序,当我的应用程序处于状态时单击通知栏时,我想根据 fcm 的数据执行操作背景,我使用下面的代码,当应用程序在前台时可以正常工作,但在后台它只是打开应用程序而不执行任何操作:

class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"
var count = 0
@SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {

if (remoteMessage.data != null && remoteMessage.data.isNotEmpty()) {
val id = remoteMessage.data["id"].toString()
val activityName = remoteMessage.data["view"].toString()
val intent = Intent(this, NewsDetailesActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
NewsDetailesActivity.currentNewId = id
startActivity(intent)

showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body,activityName,id)
}
}

private fun showNotification(title: String?, body: String?,activityName:String,id:String?) {
var intent = Intent(this, NewsDetailesActivity::class.java)
if (activityName == "news")
{
intent = Intent(this, NewsDetailesActivity::class.java)
}

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
NewsDetailesActivity.currentNewId = id!!
val pendingIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_ONE_SHOT
)

val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, "channelId")
.setSmallIcon(R.drawable.logo_orang)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(count, notificationBuilder.build())
count += 1

}
}

如何修改我的应用程序以在后台运行?

最佳答案

始终在通知 API 调用中发送数据对象像这样:

{  
"data" : {
"body" : "Watch Live Footlball Streaming online & stay updated with fastest live match scores on Hotstar",
"content_available" : true,
"title" : "Brazil vs. Denmark",
"isScheduled":false,
"scheduledTime":"2020-03-03 12:20:00",
"stationCode":"PNB",
"groupId":2

},
"to" : "epGANq1gDpE:APA91bHEuHS_QRILwI9GJ-x8Sz4DKjHRN0KX23R5TGx9HyRAN8caghmakMSnRavOf4Qwnmni3ByVRndvMjmMvfQnVt-2g6AgI5OB1-0vK3HQWDdhAjb155KWnYLXgEn763hSSbPX7tFm",
"priority" : "high"

}

此外,请检查此示例是否在后台运行。 https://github.com/googlecodelabs/android-kotlin-notifications-fcm

关于java - android:根据FCM通知的数据采取行动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57347022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com