Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 941
Gopinath Langote Avatar asked Nov 08 '22 04:11

Gopinath Langote


1 Answers

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;
    }
}}
like image 170
Suresh A Avatar answered Nov 14 '22 23:11

Suresh A