Search code examples
androidbroadcastreceiverandroid-workmanagerandroid-jobscheduler

How to trigger work manager when wifi is connected in android?


I have app which needs to sync the data as soon as internet is connected on device.

I have the sync work in Worker class and it is working fine. But I need to run this class as soon as internet is connected in phone. As broadcast receiver's on connection change is not recommended and deprecated, I need a way to fire up my class when internet is connected so that the data gets synced. How can I achieve this?

I also thought to schedule the work manager when user exists the app and keep condition of Internet connected but when app is closed from recent the onDestroy is not called. Do you have any solution or logic for this please?


Solution

  • Boy got your point. The thing you pointed out is exactly correct that you should try to avoid the broadcast receivers for such situation as people these day has large number of apps and each app firing request after internet is connected would make user's system freeze as each app want to send request after wifi is connected. Thus android system came with JET PACK after which you should not perform your app's action but request that action to android system and they will handle background request.

    As Saeed mentioned above go with

    Constraints constraints = new Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build(); 
    OneTimeWorkRequest onetimeJob = new OneTimeWorkRequest.Builder(YourJob.class)
                        .setConstraints(constraints).build(); // or PeriodicWorkRequest
    WorkManager.getInstance().enqueue(onetimeJob);
    

    But wait, you want to fire the work when internet is connected so you want some kinda thing like deprecated broadcast for connection change. Why don't you do one thing? Whenever the data you get when user is in the foreground or background use fire the work manager. If you are using retrofit for it then on it returns error when there is no internet connection thus you can schedule job when the failure is due to network.

    So you work will be

      override fun onFailure(call: Call<Chat>, t: Throwable) {
                     Log.v("chatsyncchecking","sending message failed",t)
    
                     if(t is IOException){
                         Log.v("chatsyncchecking","scheduling chat sync")
                         (app as App).enqueueChatSync()
                     }
                 }
    

    (You can fire every request from application class)

    So this make you a benefit that you should not fire work manager whenever the internet is connected. Just you fire when some task fail. This makes less work request to android system too. After all we all are the community to help android improve and users to have great experience with phone no lagging much. Hope it helps