I want to check whether internet is present or no continuously in background service so that I get broadcast as soon as the device gets connected to internet. Suggest with some snippets. Thank you.
            Asked
            
        
        
            Active
            
        
            Viewed 3,058 times
        
    2
            
            
        - 
                    what did you try up to now? – Onur A. Jul 23 '13 at 06:51
- 
                    possible duplicate of [Android - detect whether there is an Internet connection available](http://stackoverflow.com/questions/4238921/android-detect-whether-there-is-an-internet-connection-available) – Squonk Jul 23 '13 at 06:52
2 Answers
3
            Create class that extends BroadcastReceiver , use ConnectivityManager.EXTRA_NO_CONNECTIVITY to get connection info.
Code :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
public class CheckConnectivity extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent arg1) {
    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.connect.broadcast"
  android:versionCode="1"
  android:versionName="1.0" >
  <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
       <receiver android:exported="false"
          android:name=".CheckConnectivity" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
     </receiver>
   </application>
</manifest>
 
    
    
        Ronak Mehta
        
- 5,971
- 5
- 42
- 69
1
            
            
        Rather than creating Service just create intent-filter with connectivity change Developer Android
<receiver android:enabled="true" android:name=".YourReceiver"
<intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
With your BroadcastReciever:
public class YourReceiver extends BroadcastReceiver
{
 @Override
 public void onReceive( Context context, Intent intent )
 {
 }
 }
 
    
    
        Srikanth Roopa
        
- 1,782
- 2
- 13
- 19
