How to schedule a task in android which will run on immediately after internet is available and reschedule it if fails?

1.9k views Asked by At

Need scheduler to

  • Run task immediately after net is available
  • Reschedule task if it fails because of some problems.
  • should handle cases of broadcast receiver to know if connection available
  • No delay in execution if the internet is already available not like GCMNetworkManager's OneOfTask which take at least 30 seconds to execute the scheduled task

I tried GCM Network Manager's OneOfTask which handles it but takes at least 30 seconds to execute even if the internet is available.

Is there any other scheduler which will all above task in one.

4

There are 4 answers

10
Suresh A On

Use a broadcast receiver which can listen to network connectivity change. And check weather the device is connected to internet or not using ConnectivityManager. If your device is connected to the internet then schedule your task.

To use broadcast receiver. Add the following lines to manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<receiver android:name="yourpackage.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

Listener class:

package yourpackage;

public class ConnectivityReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
     final String action = intent.getAction();
     switch (action) {
        case ConnectivityManager.CONNECTIVITY_ACTION:

            ConnectivityManager connMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                //start schedule 
            }else{
                //stop schedule 
            }
            break;
    }
}}
0
bharat7777 On

For that you need to set a "Broadcast" once your device get internet off or on then a receiver will send callback to you then you can schedule task there.

0
kamlesh Mourya On

You can use BroadcastReceiver to listen network status and if network is available then start a scheduler. for scheduler you can user ScheduledExecutorService. for example..

Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() { @Override public void run() { // call tast here } }, 0, 10, IntervalTime);

1
Yogesh Borhade On
  1. No need to use Service
  2. By using broadcast also u can do it.
  3. when broadcast receive the status of internet then you can check the status and do your further .
  4. hope it helpful for you if not then please let me know i will give the code. with proper explanation.

Please click here check this link