I am working on an Android project where my app is connected to user_channel
in background and shows a notification when a new event occurs in the channel.
The Viewmodel code
@RequiresApi(Build.VERSION_CODES.O)
fun getNotifications(callback: (Payload) -> Unit) {
Coroutines.main {
repository.receiveText { msg ->
Log.d("NOTIFICATION", msg.toString())
callback(msg)
}
}
}
The Repository code
suspend fun receiveText(callback: (Payload) -> Unit) {
coroutineScope {
async {
sosChannel.on("notification") { message ->
callback(message.payload)
}
}
}
}
The Activity code
viewModel.getNotifications() {
runOnUiThread {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AlertNotification.alert(this, it["message"].toString() + "at " + it["latitude"] + " " + it["longitude"])
v.vibrate(VibrationEffect.createOneShot(1500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(1500);
}
Toast.makeText(
this,
it["message"].toString() + "at " + it["latitude"] + " " + it["longitude"],
Toast.LENGTH_LONG
).show()
}
}
Now when the app is in foreground, and my app is connected to channel , I can check for the event and it works fine But when the app is killed , the app leaves the channel an how can I keep connected to the channel to receive notification? I also learned that post Android Oreo background job is limited, despite Facebook and whatsapp like apps stay active in the backgrond ans show notifications, how do they do that - How can I proceed to achieve my goal , i.e. receiving notifications by staying connected to the channel in background an calling the Viewomdel method any suggestion is greatly appreciated , thanks in advance!