Skip to content

Instantly share code, notes, and snippets.

@Alfionte
Last active December 20, 2015 18:49
Show Gist options
  • Save Alfionte/6178819 to your computer and use it in GitHub Desktop.
Save Alfionte/6178819 to your computer and use it in GitHub Desktop.
Android Service to help you out with manage connections. Need ACCESS_NETWORK_STATE permission, add this to your Manifest <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> Use your package and enjoy it!
package com.use.your.package.here;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* @author Gabriele Porcelli
*
* Extends this Service and implement connected() && disconnected().
* Out of the box!
*/
public abstract class ConnectionService extends Service {
private BroadcastReceiver ConnectionReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();// may return
// null
if (activeNetwork != null) {
boolean isConnected = activeNetwork.isConnected();
if (isConnected) {
connected(activeNetwork.getType());
} else {
disconnected();
}
} else {
disconnected();
}
};
};
public void onDestroy() {
unregisterReceiver(ConnectionReceiver);
super.onDestroy();
};
@Override
public void onCreate() {
registerReceiver(ConnectionReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION"));
super.onCreate();
}
/**
* Handle android network connected
*
* @param Connection
* type Hint runInUIThread
*
* example
*
* switch (type) { case ConnectivityManager.TYPE_MOBILE:
* Log.i(ServiceConnection.class.getSimpleName(),
* "Connection type: Mobile"); break; case
* ConnectivityManager.TYPE_WIFI:
* Log.i(ServiceConnection.class.getSimpleName(),
* "Connection type: Wifi"); break; // API 13 case
* ConnectivityManager.TYPE_ETHERNET:
* Log.i(ServiceConnection.class.getSimpleName(),
* "Connection type: Ethernet"); break; // API 8 case
* ConnectivityManager.TYPE_WIMAX:
* Log.i(ServiceConnection.class.getSimpleName(),
* "Connection type: WiMax"); break; default: throw new
* IllegalStateException(
* "Connectivity type not supported! ConnectivityManager value:"
* + type); }
*/
protected abstract void connected(int type);
/**
* Handle Android network disconnected Hint runInUIThread
*/
protected abstract void disconnected();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment