Testing Network ( Wifi and Mobile) Connection

Following code tests whether network is available and/or connected?

package com.example.networkapidemo5b;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try
		{
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			String s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

                        ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

		}	
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), 50).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

Advertisements

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