Determine if device have an Internet Connection

Determine if device have an Internet Connection

Some of the most programmers set alarm base background services are to schedule regular updates of application for offline data synchronization. In that case I think programmers should use the BroadcastReceiver for better results. There's no need to schedule an update based on an Internet resource if you aren't connected to the Internet.

Simply use ConnectivityManager:

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

 

Your Need to add in your Manifest.xml for permission:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

Loading...

One more Manifest code need to add for receiving action:

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

 

And your actual code should be for getting intent on change network state:

public class BackgroundSync 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(TAG, "Connected" + isConnected);
        else
            Log.i(TAG, "Not Connected" + isConnected);
    }
}

 

Finally, your code look like:

Loading...
package com.legendblogs.exmpale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Created by legendblogs on 12-04-2018.
 */
public class BackgroundSync extends BroadcastReceiver {

    String TAG = "BackgroundSync";

    @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(TAG, "Connected" + isConnected);
        else
            Log.i(TAG, "Not Connected" + isConnected);
    }
}

 

Related posts

(1) Comments

  • User Pic

    Hi can we work together ?

Write a comment