Friday, February 25, 2011

Get Network Info

We can get all network info by calling getAllNetworkInfo() method of ConnectivityManager object.

Get All Network Info

AndroidNetworkInfo.java
package com.exercise.AndroidNetworkInfo;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class AndroidNetworkInfo extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectivityManager connectivityManager
= (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo
= connectivityManager.getAllNetworkInfo();

List<String> listNetworkInfo = new ArrayList<String>();
for(int i=0; i<networkInfo.length; i++){
listNetworkInfo.add(networkInfo[i].toString());
}

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listNetworkInfo));
getListView().setTextFilterEnabled(true);
}
}


Modify AndroidManifest.xml to grant permission to access network state
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exercise.AndroidNetworkInfo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidNetworkInfo"
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-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>


Download the files.

No comments: