【问题标题】:Open activity when the firebase notification is recieved without having to click the notification收到 firebase 通知时打开活动,而无需单击通知
【发布时间】:2020-11-02 18:43:15
【问题描述】:

我正在构建一个具有呼叫功能的应用程序。因此,我收到了来自服务器的通知,并构建了一个活动来显示呼叫屏幕,其中我有接听和挂断按钮。

现在我有一个问题,当应用处于后台/被杀死或手机被锁定时,我应该使用什么来启动 Activity?

我尝试在 FirebaseMessagingService 的 onMessageRecieved 函数中启动活动,但我认为当应用程序处于后台时不会调用该函数。因为当我尝试在应用程序处于后台时进行调试时,调试指针不会被触发并且活动不会打开。

Activity 在收到通知时在前台打开,但在应用处于后台时不会。

这是我的服务

class AppFirebaseMessagingService : FirebaseMessagingService() {

    private var pendingIntent: PendingIntent? = null

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.e("get_type_data", remoteMessage!!.data.toString())
        val data = remoteMessage.data
        val myCustomKey = data["notification_data"]

        if(!myCustomKey?.length?.equals(0)!!)
        {
            createNotification(remoteMessage.data)
        }

    }

    private fun createNotification(messageBody: Map<String, String>) {
        val content: String? = messageBody["content"]
        val id: String? = messageBody["id_orders"]
        val type: String? = messageBody["type"]
        var foregroud = false

        try {
            foregroud = ForegroundCheckTask().execute(this).get()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        }
        Log.e("foreground", foregroud.toString())
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val intent: Intent
        val random = Random().nextInt(1000).toString()

            if (foregroud) {
//                intent = Intent("NEW_ORDER")
//                intent.putExtra(Cons.PREF_ORDER_ID, id)
//                sendBroadcast(intent)
                intent = Intent(this, NotificationActivity::class.java)
                intent.addFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
                            or Intent.FLAG_ACTIVITY_NEW_TASK
                )
                pendingIntent = PendingIntent.getActivity(
                    this, Integer.valueOf(random)
/* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT
                )
                startActivity(intent)
            } else {
            intent = Intent(this, NotificationActivity::class.java)
                intent.addFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
                            or Intent.FLAG_ACTIVITY_NEW_TASK
                )
                pendingIntent = PendingIntent.getActivity(
                    this, Integer.valueOf(random)
/* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT
                )


              /*  intent = Intent(this, NotificationActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        or Intent.FLAG_ACTIVITY_NEW_TASK)
                pendingIntent = PendingIntent.getActivity(this, Integer.valueOf(random)
*//* Request code *//*
, intent, PendingIntent.FLAG_UPDATE_CURRENT)
                startActivity(intent)*/
            }


        if (id != null) {
            val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val notificationBuilder = NotificationCompat.Builder(this, id)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(this.resources.getString(R.string.app_name))
                .setContentText(content)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    id, getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_HIGH
                )
                channel.description = applicationContext.getString(R.string.app_name)
                channel.setShowBadge(true)
                channel.canShowBadge()
                channel.enableLights(true)
                channel.lightColor = applicationContext.getColor(R.color.colorPrimaryDark)
                channel.enableVibration(true)
                notificationManager.createNotificationChannel(channel)

            }
            notificationManager.notify(
                Integer.parseInt(id)
/* ID of notification */, notificationBuilder.build()
            )
        } else {
            Log.e("randomidforNotif", random)
            val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val notificationBuilder = NotificationCompat.Builder(this, random)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(this.resources.getString(R.string.app_name))
                .setContentText(content)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(
                    random,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_HIGH
                )
                channel.description = applicationContext.getString(R.string.app_name)
                channel.setShowBadge(true)
                channel.canShowBadge()
                channel.enableLights(true)
                channel.lightColor = applicationContext.getColor(R.color.colorPrimaryDark)
                channel.enableVibration(true)
                notificationManager.createNotificationChannel(channel)

            }
            notificationManager.notify(
                Integer.parseInt(random)
/* ID of notification */, notificationBuilder.build()
            )
        }

    }


    @SuppressLint("StaticFieldLeak")
    private inner class ForegroundCheckTask : AsyncTask<Context, Void, Boolean>() {

        override fun doInBackground(vararg params: Context): Boolean? {
            val context = params[0].applicationContext
            return isAppOnForeground(context)
        }

        private fun isAppOnForeground(context: Context): Boolean {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val appProcesses = activityManager.runningAppProcesses ?: return false
            val packageName = context.packageName
            for (appProcess in appProcesses) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName == packageName) {
                    return true
                }
            }
            return false
        }
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)

    }

}

我已关注此链接 - Open activity on firebase notification received in foreground

我也试过这个 - How to make a screen wake up when a notification is received? ---- 来唤醒设备

这是我的清单文件

    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.BIND_JOB_SERVICE"
        tools:ignore="ProtectedPermissions" />

    <uses-permission
        android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
        tools:ignore="ProtectedPermissions" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppThemeNoActionBar">
        <activity android:name=".LauncherActivity">

        </activity>
        <activity
            android:name=".NotificationActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:theme="@style/AppThemeNoActionBar">
            <intent-filter>
                <!-- Note: these actions are notification actions -->
                <action android:name="VIDEO_CALLING" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <!--<service
            android:name=".MyFirebaseMessagingService"
            android:directBootAware="true"
            android:exported="false"
            tools:targetApi="n">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>-->
        <service
            android:name=".AppFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_launcher" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id" />

        <!--

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />
        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="false" />


        <receiver android:name=".FirebaseDataReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name=".MyJobIntentService"
            android:permission="android.permission.BIND_JOB_SERVICE" />


        <service android:name="com.google.android.gms.measurement.AppMeasurementService"
            android:enabled="true"
            android:exported="false"/>

        <receiver android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.google.android.gms.measurement.UPLOAD" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

我已添加所有可能的权限和所需的元数据。

请帮助解决问题。谢谢...

【问题讨论】:

    标签: android notifications background firebase-cloud-messaging android-wake-lock


    【解决方案1】:

    在显示通知之前添加此行

    notificationBuilder.setFullScreenIntent(pendingIntent, true);
    

    【讨论】:

    • 没有帮助。我已添加,但当应用程序处于后台时,活动不会启动。只有我在系统托盘中收到通知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多