I am building an app which has a calling functionality. So I am getting a notification from server and I have built an activity to show the calling screen in which I have answer and hangup button.
Now I have a question what should I use to start the activity when the app is in background/killed or the phone is locked?
I tried to start activity in the onMessageRecieved function of a FirebaseMessagingService but I think function is not getting called when the app is in background. Because when I tried to debug the same when the app is in background the debug pointer is not triggered and the activity does not open.
The activity opens in the foreground as the notification is recieved but not when the app is in background.
Here is my Service
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)
}
}
I have follwowed this link - Open activity on firebase notification received in foreground
Also I tried this - How to make a screen wake up when a notification is received? ---- to wake up the device
Here is My manifest file
<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>
I have added all the possible permissions and meta deta required.
Please help with the solution. Thank you...