I once needed such a solution. So I crafted a class that does the trick with the codes from this site. Let's call this class iChessNetwork
:
import android.content.*;
import android.net.*;
import android.net.wifi.*;
import android.os.*;
import android.widget.*;
import java.io.*;
import java.net.*;
public class iChessNetwork {
private Context mContext;
protected Watcher mWatcher;
public iChessNetwork(Context context, Watcher watcher) {
mContext = context;
mWatcher = watcher;
init();
}
public interface Watcher {
public void Online();
}
private void init() {
registerOnlineChecker();
}
public void stop() {
unregisterOnlineChecker();
}
/*=========:INTERNET CHECK START ========*/
private BroadcastReceiver mOnlineChecker = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (isConnected()) {
//Toast.makeText(mContext,"You are connected!",Toast.LENGTH_LONG).show();
OnlineTester mOnlineTester = new OnlineTester();
mOnlineTester.execute();
}
}
};
private void registerOnlineChecker() {
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mOnlineChecker, filter);
}
private void unregisterOnlineChecker() {
mContext.unregisterReceiver(mOnlineChecker);
}
private boolean isConnected() {
boolean isMobile = false, isWifi = false;
ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] infoAvailableNetworks = cm.getAllNetworkInfo();
if (infoAvailableNetworks != null) {
for (NetworkInfo network : infoAvailableNetworks) {
if (network.getType() == ConnectivityManager.TYPE_WIFI) {
if (network.isConnected() && network.isAvailable())
isWifi = true;
}
if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
if (network.isConnected() && network.isAvailable())
isMobile = true;
}
}
}
return isMobile || isWifi;
}
/*========= INTERNET CHECK END ==========*/
private class OnlineTester extends AsyncTask<Void,Void,Boolean> {
public OnlineTester() {
}
@Override
protected Boolean doInBackground(Void[] p1) {
boolean online = false;
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
if (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0) {
//Log.d("Network Checker", "Successfully connected to internet");
online = true;
}
} catch (IOException e) {
online = false;
}
return online;
}
@Override
protected void onPostExecute(Boolean online) {
// TODO: Implement this method
super.onPostExecute(online);
if(online) {
if(mWatcher != null) {
mWatcher.Online();
}
}
}
}
};
As you may notice, there is an interface in the class. Basically, I want to know if an "active" internet connection is available or not from one of my Activity
classes. So I implemented above interface
in that Activity
as follows:
public class YourActivity extends Activity implements iChessNetwork.Watcher {
private iChessNetwork mNetwork;
@Override
public void Online() {
// It's online now - do your connection
}
By now, we're ready to go. So I let it run from somewhere (usually, in onCreate()
, an android app start point) in the Activity
class:
mNetwork = new iChessNetwork(this, this);
And I start tracking "active" internet connection from this point and stop tracking when I don't want it (usually, in onBackPressed()
and onDestroy()
methods of my Activity
like this:
if(mNetwork != null) {
mNetwork.stop();
}
Hope this helps you and someone else.