9.3 Android Network Connectivity

Hello ReadersJ!!! Hope you are doing great. Today we are going to learn about networks. All of us are aware of the importance of internet. So it is very essential to understand the mechanism of connectivity for our better understanding of concept. So let us not waste time and start diving deep into this.

9.3.1 Introduction

ConnectivityManager represents the Network Connectivity Service. It is used to monitor the state of network connections, control the coverage of network and configuration of the failover settings. Application needs read and write network state access permissions to use the Connectivity Manager. These permissions are:

•    <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE”/>
•    <uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE”/>

To access Connectivity Manager we use getSystemService and we pass the Context.CONNECTIVITY_SERVICE as the service name.

 

9.3.2 Background Data Transfers and Managing Network Connectivity

Before Android 4.0 platforms we were responsible for adhering to the user preferences. This is useful for allowing background data transfers. User preferences for background data transfers are enforced at application level. We call the getBackgroundDataSetting method on the Connectivity Manager method to obtain the background data setting. If the background setting is disabled, application should transfer data only when it is active and it is in foreground. This value is turned off so that user explicitly requests that application to not to transfer data when it is not visible.

If user does change the background data preference then the system will send a broadcast intent with the Connectivity Manager’s ACTION_BACKGROUND_DATA_SETTING_CHANGED action. To monitor changes in the background data setting we create and register a new broadcast receiver which listens for this broadcast intent.

In Android 4.0 and above, getBackgroundDataSettiing has been deprecated. It always returns true. Now users have much more control over the network data usage of applications. We can set individual data limits and restrict background data. Now preferences are set at system level. If data transfer is unavailable and it attempts to transfer data or check network connectivity it will fail. Device will appear to be offline. We create a preference activity which allows users to modify applications’ data usage. We make it available from within the system settings when a user inspects your application’s data usage. 

Connectivity Manager provides a view of the available network connections. The getActiveNetworkInfo method returns a NetworkInfo object which includes the details of available networks. We can find the details of inactive network by using the getNetworkInfo method. Before performing any data transfer related activities we should always use Connectivity Manager to check whether we are actually connected to internet or not.

I understand that you are getting confused and bored with all of these sophisticated theories. Don’t worry even I was feeling the same thing when I studied these concepts for the first time. I am here to resolve your issues. Let us create a small example and find out the simple usage of these jargons.

9.3.3 Example

Create a project and name it as you like. I am naming it ConnectionDetectorEx app. In this example we shall develop an application which will detect whether device is connected to internet or not. So let us start developing. Open your activity_main.xml file and populate the file as shown in the following listing:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/internetand"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Readers" />
    <Button
        android:id="@+id/btn_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Check Internet Status" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="23dp"
        android:text="Detect Internet Status" />
</RelativeLayout>

Figure activity_main.xml file

The graphical layout of this application is as shown in the following snapshot:

Figure Graphical layout of application

Now open the main activity file and populate the class as shown in the following listing:

package com.android.tution.ConnectionDetector;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    // flag for Internet connection status
    Boolean isInternetPresent = false;
    // Connection detector class
    ConnectionDetector cd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnStatus = (Button) findViewById(R.id.btn_check);
        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        /**
         * Check Internet status button click event
         * */
        btnStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // get Internet status
                isInternetPresent = cd.isConnectingToInternet();
                // check for Internet status
                if (isInternetPresent) {
                    // Internet Connection is Present
                    // make HTTP requests
                    showAlertDialog(MainActivity.this, "Internet Connection",
                            "You have internet connection", true);
                } else {
                    // Internet connection is not present
                    // Ask user to connect to Internet
                    showAlertDialog(MainActivity.this,
                            "No Internet Connection",
                            "You don't have internet connection.", false);
                }
            }
        });
    }

Figure First half of class

Second half of main activity is as shown in the following listing. Please continue coding in the same class:

@SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        // Setting Dialog Title
        alertDialog.setTitle(title);
        // Setting Dialog Message
        alertDialog.setMessage(message);
        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Figure Second half of code

As you can see, there are lots of errors in your code. Don’t worry we will sort out this. Create an inner class and name it ConnectionDetector. Now populate this java class with the following lines of code:

package com.android.tution.ConnectionDetector;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
    private Context _context;
    public ConnectionDetector(Context context) {
        this._context = context;
    }
    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

Figure ConnectionDetector.java

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.tution.ConnectionDetector"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.tution.ConnectionDetector.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Figure manifest file

Create a suitable emulator and run the application. The emulator should look similar to the following snapshot:

Figure Emulator after first run of application

You might think this author is fooling us. So to prove my innocence I have shown my internet connection manager. You can see my device is connected to internet. This application can be tested on emulator. So the output should look similar to the following snapshot: 

Figure App detects the internet connectivity

I am also attaching the pictures of app running on a real device. This module was a part of another application so the name would be sensors, not ConnectionDetectorEx. But rest of the things is same. 

Figure Application as seen on the real device

Figure Output of application when device was not connected to internet

Figure Output of app when device is connected to internet

Congratulations buddiesJ!! We are done with coding part. Hope you enjoyed developing this app. See you in the next section. Till then keep practicing. Happy App Developing!!