DEVANG SHARMA
DEVANG SHARMA

Reputation: 2662

making background thread to check if network available and notify when ever it is available

I made a service and a Activity, I need the processing in the following Manner

Like the service starts automatically at application boots up, and check periodically if there is network available or not, and whenever it is available then notify to the user.

How i can do this, i want some alarm manager or blinking screen until the network is available

Thank You

Upvotes: 1

Views: 828

Answers (1)

Ovidiu Latcu
Ovidiu Latcu

Reputation: 72321

You should make an BroadcastReceiver that will be triggered when the connectivity status has changed, by adding this in your manifest:

   <receiver
        android:name=".receivers.NetworkChangeReceiver"
        android:label="NetworkChangeReceiver">
        <intent-filter>
            <action
                android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action
                android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

and then in your receiver you can check if you have connectivity:

   public class NetworkChangeReceiver extends BroadcastReceiver{

   @Override
   public void onReceive(Context context, Intent intent) {
       ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       if(cm.getActiveNetworkInfo()!=null&&cm.getActiveNetworkInfo().isConnected()){
           //Send a broadcast to your service or activity that you have network
           //...
       }else{
           LOG.i("Network UNAVAILABLE");
       }
   }

}

Upvotes: 5

Related Questions