Skip to content

Instantly share code, notes, and snippets.

@Fullplate
Created July 15, 2014 00:07
Show Gist options
  • Save Fullplate/2ebba9a689b17775af79 to your computer and use it in GitHub Desktop.
Save Fullplate/2ebba9a689b17775af79 to your computer and use it in GitHub Desktop.
Android Connection Checking
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
/**
* Checks for a network connection at intervals until connection is found, or timeout has been reached.
* Result is sent via a message containing {"connected":boolean} sent to passed-in Handler.
* Log output is sent via a message containing {"log":string} sent to passed-in Handler.
* Handle one bundle key-value pair per message.
*/
public class ConnectionChecker implements Runnable {
private ConnectivityManager connManager;
private Handler handler;
private int timeBetweenChecks;
private int timeout;
private int elapsedTime;
public ConnectionChecker(ConnectivityManager connManager, Handler handler, int timeBetweenChecks, int timeout) {
this.connManager = connManager;
this.handler = handler;
this.timeBetweenChecks = timeBetweenChecks;
this.timeout = timeout;
this.elapsedTime = 0;
}
@Override
public void run() {
NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo();
// if we detect a connection, send "true" result
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
sendResult(true);
}
else {
// otherwise, if waiting to retry will put us past timeout, send "false" result
if ((elapsedTime + timeBetweenChecks) > timeout) {
sendResult(false);
}
// otherwise we can check again in x seconds
else {
sendLog("Retrying network connectivity in "+timeBetweenChecks+" seconds");
elapsedTime += timeBetweenChecks;
handler.postDelayed(this, timeBetweenChecks * 1000);
}
}
}
private void sendResult(boolean connected) {
Bundle bundle = new Bundle();
bundle.putBoolean("connected", connected);
Message message = new Message();
message.setData(bundle);
handler.dispatchMessage(message);
}
private void sendLog(String log) {
Bundle bundle = new Bundle();
bundle.putString("log", log);
Message message = new Message();
message.setData(bundle);
handler.dispatchMessage(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment