Я создаю приложение, которое имеет функцию вызова. Итак, я получаю уведомление с сервера, и я создал действие, чтобы показать экран вызова, на котором у меня есть кнопка ответа и отбоя.
Теперь у меня есть вопрос, что я должен использовать для запуска активности, когда приложение находится в фоновом режиме/убито или телефон заблокирован?
Я попытался начать активность в функции onMessageRecieved FirebaseMessagingService, но я думаю, что функция не вызывается, когда приложение находится в фоновом режиме. Потому что, когда я пытался отладить то же самое, когда приложение находится в фоновом режиме, указатель отладки не срабатывает, и действие не открывается.
Активность открывается на переднем плане при получении уведомления, но не когда приложение находится в фоновом режиме.
Вот мой сервис
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)
}
}
Я перешел по этой ссылке - Открыть активность в уведомлении Firebase, полученном на переднем плане а>
Также я пробовал это - Как сделать экран просыпается при получении уведомления? ---- чтобы разбудить устройство
Вот мой файл манифеста
<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>
Я добавил все возможные разрешения и необходимые метаданные.
Пожалуйста, помогите с решением. Спасибо...