websockets on Android and iOS

前端 未结 1 473
一向
一向 2021-01-25 18:20

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

相关标签:
1条回答
  • 2021-01-25 18:58

    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

    0 讨论(0)
提交回复
热议问题