How to detect network status change(realtime)
How to get network status change realtime?
When is disconnecting network? When is connecting network?
To apply network status detection How to detect Network Status, I will detect network status at the realtime.
Steps
- Create BroadcastReceiver to detect
- Register this BroadcastReceiver
Register
I suggest 2 ways to register BroadcastReceiver
Detect Application Level
Detect everywhere in Application(like NSNotification)
At first, extends BroadcastReceiver class and use network connection code.
public class NetworkConnectionReceiver extends BroadcastReceiver { //private static String TAG = "NetworkConnectionReceiver"; @Override public void onReceive(Context context, Intent intent) { ConnectivityManager manager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean connect = NetworkConnection.isConnected(manager); //String message = connect ? "Connect" : "Disconnect"; //Log.d(TAG, message); //Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } }
<receiver android:name=".network.NetworkConnectionReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"> </action></intent-filter> </receiver>
The point is android.net.conn.CONNECTIVITY_CHANGE
How to test?
While running application, make wifi off, you can see change status in Logcat.
Detect within an Acitivity
Create instance of this class and register
If you want change UI, you should create it as inner class
NetworkConnectionReceiver receiver = new NetworkConnectionReceiver(); intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(receiver, intentFilter);