Search code examples
androidbroadcastreceiverandroid-broadcastreceiver

How to run a service only when internet is connected?


Hello I am new to android and I almost complete my app. But I am stuck with the problem now. I want to run a service which works only when internet is connected or disconnected. I used Brodcast receiver for that and also registered that brodcast in an activity of an app. But its not working when I am trying when app gets killed, reciever get called but it shows no internet is connected.

Brodcast Receiver:

public class ImageDownloadReceiver extends BroadcastReceiver {

public static boolean isConnected(Context context){
    ConnectivityManager
            cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}


@Override
public void onReceive(Context context, Intent intent) {
    Log.i("Info", "onReceive in ImageDownloadReceiver get called ... ");

    if(isConnected(context)){
        Log.i("Info", "Internet connected !!!...Service starts ... ");
        Intent myService = new Intent(context, ImagesDownloadService.class);
        context.startService(myService);
    }else{
        Log.i("Info", "Internet disconnected !!!...Service stops ... ");
        Intent myService = new Intent(context, ImagesDownloadService.class);
        context.stopService(myService);
    }
}
}

Manifest:

    <receiver
        android:name=".receiver.ImageDownloadReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped">
        <intent-filter>
            <action android:name="com.example.app.RestartImageDownloadService"/>
            <action
                android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>

Solution

  • I suggest you prefer to use JobScheduler to handle your case. JobScheduler provide you a service and a lot of conditions to start the service. Of course, these conditions consist of internet connectivity. Here you go: https://developer.android.com/reference/android/app/job/JobScheduler.html