Reputation: 729
I'm creating a mobile app that has an instant messaging capability. I am coming up with the backend before I will employ someone to develop the mobile component. The main way for communication between the mobile device (client) and server will be via a websocket. I've heard that once an application is no longer in the foreground on mobile devices (both android and iOS) the websocket closes.I don't wantt to spend the time developing the server around websockets to realise i can't use this technology for this purpose down the line. Could someone please assist me with the following questions:
If this is the case (web socket closes in the background) how do applications like bumble and what's app continue to show near time notifications?
How can the socket continue to run in the background? Is there there better newer technology for doing this?
UPDATE The question here is how to maintain a persistent websocket when the applications isn't in the foreground. I would like to know more about how iOS and android handle the situation when an application is minimised. Do the websockets continue to run? or are they closed? Do other libraries have to be used to make this keep running?
Upvotes: 2
Views: 2599
Reputation: 7209
ANDROID:
As Android is focusing on the efficient way of using the battery, the system deprives the resources of the app when the app is in the background(Dependent). It is better to use the work manager to handle your background tasks.
Take a look https://developer.android.com/topic/libraries/architecture/workmanager/basics.html
Sample code
class GetMessages(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
getAndSaveMessages()
return Result.success()
}
private fun getAndSaveMessages() {
// get messages here
}
}
Put this code in a Singleton class to access it from anywhere Like JobManager
object JobManager{
private fun syncMessages(){
val loadMessages = PeriodicWorkRequestBuilder<GetMessages>(5, TimeUnit.MINUTES)
// Add tag to cancel the thread any time
loadMessages.addTag("MESSAGES")
val myConstraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
// Many other constraints are available, see the
// Constraints.Builder reference
.build()
// Add constraints
loadMessages.setConstraints(myConstraints)
WorkManager.getInstance().enqueue(loadMessages.buld())
}
}
Now you can use JobManager.syncMessages()
from anywhere
Upvotes: 2