(安卓系统)当收到firebase云消息时(即使应用程序是backgorund),有没有办法显示AlertDialog



我想在收到Firebase云消息时显示AlertDialog(Android应用程序是前台还是后台(。

在forground中,应用程序显示AlertDialog,但在后台,应用程序不显示AlertDialog。

MyFirebaseMessageService.kt

class MyFirebaseMessageService : FirebaseMessagingService() {
private val TAG = "fcm_tag"
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val title = remoteMessage.notification?.title
val body = remoteMessage.notification?.body
Log.d(TAG, "fcm title: $title")
Log.d(TAG, "fcm body: $body")
val alertDialogIntent = Intent(baseContext, AlertDialogActivity::class.java)
alertDialogIntent.putExtra("title", title)
alertDialogIntent.putExtra("body", body)
try {
PendingIntent.getActivity(
baseContext,
0,
alertDialogIntent,
PendingIntent.FLAG_IMMUTABLE
).send()
} catch (e: Exception) {
Log.d(TAG, "fcm error: $e")
}
}
}

AlertDialogActivity.kt

class AlertDialogActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bund = intent.extras
val title = bund?.getString("title")
val body = bund?.getString("body")
AlertDialog.Builder(this).run {
setTitle(title)
setMessage(body)
setPositiveButton("OK") { _, _ ->
finish()
}
setCancelable(false)
show()
}
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.myproject">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyProject">
<service
android:name=".MyFirebaseMessageService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".AlertDialogActivity"
android:exported="true"
android:theme="@style/Theme.AppCompat.DayNight.Dialog">
</activity>
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.MyProject">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="fcm_default_channel" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_launcher_foreground" />
</application>
</manifest>
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Are you sure?")
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

并请求此权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

相关内容

  • 没有找到相关文章

最新更新