1

I am new in android. I want to set up a broadcast receiver which receives only once when the internet connection is changed. I have set up one but it receives at least 3 times. Could any one please help me.

in androidmainfest.xml

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

public class NetworkServices extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
       ConnectionDetector cd = new ConnectionDetector(context);
       Boolean isInternetPresent = cd.isConnectingToInternet();
        if(isInternetPresent){          
            new DoAsyncTask().execute(context);
        }

    }
}
Sara
  • 325
  • 2
  • 3
  • 13

2 Answers2

0

In the first case:

ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
and check (e.g.):
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)

In the second case you can register a receiver for system wide network change event as described here: Broadcast receiver for checking internet connection in android app after that if you do not want to receive anymore you can use something like:

 PackageManager pm = getPackageManager();
   ComponentName compName = 
        new ComponentName(getApplicationContext(), 
            ConnectivityChangeReceiver.class);
   pm.setComponentEnabledSetting(
        compName,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 
        PackageManager.DONT_KILL_APP);

But only once. If you need to do every day you must use alarm manager and android service.

Community
  • 1
  • 1
aorlando
  • 668
  • 5
  • 21
0

I think u misunderstanding the meaning of each broadcast. The three consequence connection changes contain different meaning

I assume you only need connected/not connected So thats all u need

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {
        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

        if (noConnectivity) {
            //not_connnected statement    
        } else {
             //connected statement
    }
      }
}

http://developer.android.com/reference/android/net/ConnectivityManager.html Dump EXTA_INFO of each broadcast, and you will find more info

楊惟鈞
  • 622
  • 6
  • 12