RSS

Code to check the network connection in android

19 Jun

– To check the network connection in android we use ConnectivityManager.
– Which returns the status of network availability in terms of boolean. i.e. true/false

public static void checkNetworkConnection(Activity context){
		AlertDialog.Builder objBuilder;
		ConnectivityManager objConnectivityManager ;
		AlertDialog alertforinternetstatus;
		try{
			objConnectivityManager = (ConnectivityManager)context.getSystemService(Activity.CONNECTIVITY_SERVICE);
			final boolean IsWifiAvailable = objConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
			final boolean IsInternetAvailable = objConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
			if(IsWifiAvailable == true || IsInternetAvailable == true){
				Toast.makeText(context, "Connection Available.", Toast.LENGTH_SHORT).show();
			}
			else{
				objBuilder = new AlertDialog.Builder(context);
				objBuilder.setMessage("You must be connected to the internet or Wi-Fi to proceed futher.")
				.setCancelable(false)
				.setTitle("Connection Error")
				.setNegativeButton("OK", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int id){
						dialog.cancel();
					}
				});
				alertforinternetstatus = objBuilder.create();
				alertforinternetstatus.show();
			}
		}
		catch (Exception e){
			e.toString();
		}
		finally{
			objBuilder = null;
			objConnectivityManager=null;
			alertforinternetstatus=null;
		}
	}

Also don’t forget to add permission in manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Advertisements
 
Leave a comment

Posted by on June 19, 2012 in Android Source Code

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: