Tuesday, May 26, 2009

Permissions Journey: ACCESS_NETWORK_STATE

ACCESS_NETWORK_STATE as what the description on the permissions page stated, it allows your application to access information about your network. To use this permissions.

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

Main.java
ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conMan.getActiveNetworkInfo();
Log.d("Connected state",networkInfo.getState().toString());
if(networkInfo.isConnected()){
  Log.d("Connected",networkInfo.toString());
}

Explanation
First we need to get the system service that answers queries about the state of network connectivity.
ConnectivityManager conMan = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

Then we get our active network
NetworkInfo networkInfo = conMan.getActiveNetworkInfo();

We then check the current state of the network
Log.d("Connected state",networkInfo.getState().toString());

We check if this network is connected or not
if(networkInfo.isConnected()){ ...... }

If our network is connected then most likely we would do our magic on that block, but for now let us trace the network
Log.d("Connected",networkInfo.toString());

References
ConnectivityManager
NetworkInfo
http://www.google.com/codesearch/p?hl=en#MkYB9wOx8C4/trunk/DroidGuide/Client/src/br/ufmg/ubicomp/droidguide/utils/AndroidUtils.java&q=networkinfo%20android

Update History
   Jan 17, 2012 - Visual Update
Post a Comment