Skip to content

Instantly share code, notes, and snippets.

@florian-do
Last active September 5, 2018 22:06
Show Gist options
  • Save florian-do/f8f43b88ad7fe76527482513fe003ba3 to your computer and use it in GitHub Desktop.
Save florian-do/f8f43b88ad7fe76527482513fe003ba3 to your computer and use it in GitHub Desktop.
A simple network listener
package com.azconception.taxi.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;
/**
* Created by do_f on 28/07/16.
*/
public class MyNetworkReceiver extends BroadcastReceiver {
private static final String TAG = MyNetworkReceiver.class.getSimpleName();
public static final int NETWORK_OFF = 0;
public static final int NETWORK_ON = 1;
private OnNetworkStateChanged mListener;
@Override
public void onReceive(Context context, Intent intent) {
if (mListener != null) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null) {
mListener.onStateChange(NETWORK_ON);
} else {
mListener.onStateChange(NETWORK_OFF);
}
}
}
public interface OnNetworkStateChanged {
void onStateChange(int state);
}
public OnNetworkStateChanged getmListener() {
return mListener;
}
public void setmListener(OnNetworkStateChanged mListener) {
this.mListener = mListener;
}
}
public class MainActivity extends AppCompactActivity {
protected void initNetwork() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
network = new MyNetworkReceiver();
registerReceiver(network, filter);
network.setmListener(this);
isNetworkRegistered = true;
}
@Override
protected void onResume() {
super.onResume();
if (!isNetworkRegistered && network == null)
initNetwork();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregisters BroadcastReceiver when app is destroyed.
if (network != null && isNetworkRegistered) {
isNetworkRegistered = false;
this.unregisterReceiver(network);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment