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 f
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