问题
I have broadcast receiver for "CONNECTIVITY_CHANGE". When I print the extra using this:
intent.getExtras().toString()
I can see that if I disable WIFI, I receive 2 network change.
- WIFI DISCONNECTED
- MOBILE CONNECTED
However, when I try to use
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
It said, this API has been deprecated. After that, I tried to use this
int networkType = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_TYPE);
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(networkType);
However, getNetworkInfo also has been deprecated.
The only option they give me was using getActiveNetworkInfo or getActiveNetwork.
If I use that, I will get 2 broadcast which will give me same network info.
Is there a better way to handle network state in Android ?
EXTRA NOTE:
Thanks for quick reply, but I am not looking for a way to check if I have internet connection or not.
I need to know which network has been disconnected and connected. The network state change is what I am looking for.
回答1:
Here is a simple code snippet that will help you identify what kind of internet connection a user has on her device.
First we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.
Permissions required to access network state:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now check following utility class NetworkUtil. It has method getConnectivityStatus which returns an int constant depending on current network connection. If wifi is enabled, this method will return TYPE_WIFI. Similarly for mobile data network is returns TYPE_MOBILE. You got the idea!!
There is also method getConnectivityStatusString which returns current network state as a more readable string.
Create a class NetworkUtil.java and paste the following code:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
You can use this utility class in your android app to check the network state of the device at any moment.
Broadcast Receiver to handle changes in Network state
You can easily handle the changes in network state by creating your own Broadcast Receiver. Following is a broadcast receiver class where we handle the changes in network.
Check onReceive() method. This method will be called when state of network changes. Here we are just creating a Toast message and displaying current network state. You can write your custom code in here to handle changes in connection state.
Create a class NetworkChangeReceiver.java and paste the following code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
Once we define our BroadcastReceiver, we need to define the same in AndroidMenifest.xml file. Add following to your manifest file.
<application ...>
...
<receiver
android:name="YOUR PACKAGE NAME"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
...
</application>
We defined our broadcast receiver class in manifest file. Also we defined two intent CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED. Thus this will register our receiver for given intents. Whenever there is change in network state, android will fire these intents and our broadcast receiver will be called.
That's it Run Your Code.Hope this serves your purpose !!
回答2:
Use the below code and check the network connectivity current status
public class NetworkStateReceiver extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
this.context = context;
Log.d("app","Network connectivity change==>"+isOnline());
if(isOnline()==true)
{
//Internet Connected!
}
else
{
// No Internet!
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
}
回答3:
Determine if You Have an Internet Connection
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
Determine the Type of your Internet Connection
Device connectivity can be provided by mobile data, WiMAX, Wi-Fi, and ethernet connections. By querying the type of the active network, as shown below, you can alter your refresh rate based on the bandwidth available.
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
Monitor for Changes in Connectivity
Apps targeting Android 7.0 (API level 24) do not receive CONNECTIVITY_ACTION broadcasts even if they register those broadcasts in their manifest. Apps that are running can still listen for CONNECTIVITY_CHANGE on their main thread by registering a BroadcastReceiver with Context.registerReceiver().
回答4:
You can use this to check the internet is available or not:
/**
* Check Internet connection is available or not
*
* @param context current context
* Use {@link #checkInternetConnection(Context context)}
* @return {@link Boolean}
*/
public static boolean checkInternetConnection(Context context) {
ConnectivityManager _connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean _isConnected = false;
NetworkInfo _activeNetwork = _connManager.getActiveNetworkInfo();
if (_activeNetwork != null) {
_isConnected = _activeNetwork.isConnectedOrConnecting();
}
return _isConnected;
}
回答5:
Use Broadcast Receiver :
Manifest Entry:
<receiver android:name=".your.namepackage.here.ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
class for receiver:
public class ConnectivityReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case ConnectivityManager.CONNECTIVITY_ACTION:
if(isConnect()) //your logic to check netwrok
{
//do action here
}
break;
}
}
}
回答6:
try this code
public static boolean isActiveNetworkMetered(Context context) {
ConnectivityManager manager = getConnectivityManager(context);
if (manager == null)
return false;
ConnectivityManagerCompat compat = new ConnectivityManagerCompat();
return compat.isActiveNetworkMetered(manager);
}
public static String getActiveNetworkName(Context context) {
try {
NetworkInfo info = getActivieNetworkInfo(context);
String typeName = info.getTypeName().toLowerCase();
if (typeName.equals("wifi")) {
return typeName;
} else {
String extraInfoName = info.getExtraInfo().toLowerCase();
if (!TextUtils.isEmpty(extraInfoName))
return extraInfoName;
}
return typeName;
} catch (Exception e) {
return null;
}
}
来源:https://stackoverflow.com/questions/40713270/how-to-get-network-state-change-on-android