Thursday, March 3, 2011

Get Detailed Network State of Android device

Via ConnectivityManager, the detailed state of all network device can be get.

Get Detailed Network State of Android device

Keep using AndroidManifest.xml of last exercise "Get Network Info" to grant permission of "android.permission.ACCESS_NETWORK_STATE".

Call getDetailedState() method of NetworkInfo object to get the detailed state.
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++){
String strNetworkState = networkInfo[i].getTypeName()
+ " : "
+ networkInfo[i].getDetailedState();

listNetworkInfo.add(strNetworkState);
}

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


Download the files.

No comments:

Post a Comment