Search code examples
androidusingbroadcast

How to make call to service from receiver depends on Internet connected or not?


I know how to checking if internet is available or not in the activity, my requirement is, actually i am storing some values in DB when the device in offline ( no internet), when it comes to online have to pass DB values to the server with out user interactivity. how can i achieve this. i got this example How to check the Internet Connection periodically in whole application? but it's working only for one activity , how to make it as global.


Solution

  • Use this in your receiver

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

    Your UpdateRecieiver

     public class UpdateReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
          ConnectivityManager connectivityManager = (ConnectivityManager) 
                                       context.getSystemService(Context.CONNECTIVITY_SERVICE );
          NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
          boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();   
          if (isConnected)       
              Log.i("NET", "connecte" +isConnected);   
          else Log.i("NET", "not connecte" +isConnected);
        }
    }