Tuesday, November 27, 2012

How To Detect Data Connection In Android

In one of our past tutorials you have learned to detect if you have internet connection by way of checking if your Android smartphone is in airplane mode. But what if it isn’t in airplane mode?

Android provides a way to turn on/off your data connection (which enables/disables you to send sms and surf the internet) through its Settings | Wireless & Networks | Mobile Network menu. And from there you can toggle on/off the Data enabled switch.

Programmatically, you can detect the data state of your smartphone. Just implement the code below on you main java file.

    public boolean isDataConnectionAvailable() {        boolean lRet = false;        try{            ConnectivityManager conMgr =  ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo info= conMgr.getActiveNetworkInfo();              if(info != null && info.isConnected()) {                  lRet = true ;            }else{                  lRet = false ;            }            Log.d("isDataConnectionAvailable", "Normal execution...");        }catch (Exception e) {            Log.d("Connection Error", e.toString());            lRet = false ;       }        return lRet;      }

And on your AndroidManifest.xml file add the following:

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

To test this method, just add the following codes in you main Activity file:

if (isDataConnectionAvailable()) {   Toast.makeText(this, "Data connection is enabled.", Toast.LENGTH_SHORT).show();} else {   Toast.makeText(this, "Data connection is disabled.", Toast.LENGTH_SHORT).show();}

By informing users of your app about their data state it will even make your Android app more user-friendly.

Related Posts:

Tags: android tutorial


Source : htmlpress[dot]net

0 comments:

Post a Comment