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();
}
}
android:name=".yourPath.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</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:
<receiverandroid: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" />
public void onConnectionChange() {
// do something here...
}
networkChangeReceiver.setNetworkListener(null);
unregisterReceiver(networkChangeReceiver);
}
Step 2: Implement in Activity:
- Create field:
private NetworkChangeReceiver networkChangeReceiver;
- Implements NetworkChangeReceiver.NetworkListener
- Ctrl + I:
@Overridepublic void onConnectionChange() {
// do something here...
}
- OnStart() of Activity:
if (networkChangeReceiver == null)
networkChangeReceiver = new NetworkChangeReceiver();
networkChangeReceiver.setNetworkListener(this);
registerReceiver(networkChangeReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
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
Đăng nhận xét