Using the Connectivity API

Connectivity API is supported via ConnectivityManager. As always, you get this manager fro the system via getSystemService(). Once you have the manager, you can get info for various networks, namely WiFi and mobile. In this example, we simply print this info out to a TextView.


ConnectivityDemo.java:
Code:

package com.marakana;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;

public class ConnectivityDemo extends Activity {
ConnectivityManager connectivity;
NetworkInfo wifiInfo, mobileInfo;

TextView textStatus;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get UI
textStatus = (TextView) findViewById(R.id.textStatus);

// Setup Connectivity
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

// print info
textStatus.append("\n\n" + wifiInfo.toString());
textStatus.append("\n\n" + mobileInfo.toString());
}
}

The layout for this example is trivial - it contains one TextView for the output from our activity.

/res/layout/main.xml:

Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/textStatus"
android:text="Connectivity Demo" />
</LinearLayout>


Finally, don't forget to add the proper permission declarations to your AndroidManifest.xml file:
AndroidManifest.xml:

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".ConnectivityDemo" 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>
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</manifest>


The final output should look like this:




Source Code:

https://www.protechtraining.com/static/tutorials/ConnectivityDemo.zip

Copyright © 2018 ProTech. All Rights Reserved.

Sign In Create Account

Navigation

Social Media