Friday, 10 October 2014

Android - how to check internet connection programmatically

I will show simple code to check internet connection status in android device programmatically.

Please try it your self.

package com.j4android;

import android.app.Activity;                     

import android.os.Bundle;

public class MainActivity extends Activity{
Boolean isInternetPresent = false;
ConnectionDetector cd;
    @Override
    public void onCreate(Bundle bundle){
super.onCreate(bundle);
setContentView(R.layout.main);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
Toast.makeText(getApplicationContext(), isInternetPresent+"",
Toast.LENGTH_SHORT).show();
//Do something here
} else {
Toast.makeText(getApplicationContext(), isInternetPresent+"",
Toast.LENGTH_SHORT).show();
}              
    }

}

ConnectionDetector.java


package com.j4android;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context) {
this._context = context;
}

public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}

}

Don't forget to add these two permissions in the manifest file.


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

No comments:

Post a Comment