In Android To Check the Internet Connection is Available for Frequently?

android, netconnection, service

Solution

You can do it without any timers, just register receiver for listening connection changes:

<receiver android:name=".ReceiverName" >
    <intent-filter >
        <action android:name="android.net.wifi.STATE_CHANGE" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

And check if connection established:

public class ReceiverName extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
        if (cm == null)
            return;
        if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
            // Send here
        } else {
            // Do nothing or notify user somehow
        }

    }
}

Problem

Hai my Application is to Save (to Server) the Data through NetConnection. If net is not Available i saved Locally, and then when net is available again send to the server. My problem is to check Internet Connection Frequetly.So i tried the Service function for checking the Net connection. But it called once only. How to solve my Problem. Anybody kindly help me Thanks in advance! update ``` package com.android.cdtech; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.ConnectivityManager; import android.view.View; class ReceiverName extends Activity { BroadcastReceiver r = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)); if (cm == null) return; if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { saveData(); } else { // Do nothing or notify user somehow } } // code to handle broadcase private void saveData() { final saveData dh=new saveData(this); //Class for Creating a Database webService calService=new webService(); dh.open(); Cursor c = dh.pay(); String text = ""; do { text = text + " " + "\n" + c.getString(4); System.out.println(c.getCount()); // Toast.makeText(this,"Name:" +c.getString(1)+c.getString(2)+c.getString(3)+c.getString(4)+"",Toast.LENGTH_LONG).show(); calService.paymentReceipt("PaymentReceipt", c.getString(1), c.getString(2), c.getString(3), c.getString(4), "gf", "0"); } while (c.moveToNext()); dh.close(); } }; } ```

Original source