Android - Auto detect network connection change event - Java

Step 1: Create a Receiver

- Create class NetworkChangeReceiver:

public class NetworkChangeReceiver extends BroadcastReceiver {
private NetworkListener networkListener;

public void setNetworkListener(NetworkListener networkListener) {
this.networkListener = networkListener;
}

public NetworkChangeReceiver() {

}

@Override
public void onReceive(Context context, Intent intent) {
if(networkListener!=null)
networkListener.onConnectionChange();
}

public interface NetworkListener {
void onConnectionChange();
}
}

- In AndroidManifest.xml add in tag application:
<receiver
android:name=".yourPath.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

- Add permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 2: Implement in Activity:
- Create field: 
private NetworkChangeReceiver networkChangeReceiver;
- Implements NetworkChangeReceiver.NetworkListener
- Ctrl + I:
@Override
public void onConnectionChange() {
// do something here...
}
- OnStart() of Activity:
if (networkChangeReceiver == null) 
networkChangeReceiver = new NetworkChangeReceiver();
networkChangeReceiver.setNetworkListener(this);

registerReceiver(networkChangeReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

- OnStop() in Activity:
if (networkChangeReceiver != null) {
networkChangeReceiver.setNetworkListener(null);
unregisterReceiver(networkChangeReceiver);
}

Nhận xét

Bài đăng phổ biến từ blog này

Android - Date Time - Lấy giá trị ngày, giờ theo định dạng tùy biến trong Android Studio

Android - Image - Take Photo, Choose Photo from Gallery - Xử lý chụp ảnh, lấy ảnh trong Android Studio

Android - Circle Image - Tạo ảnh bo tròn trong Android Studio