如果您声明了一个 BroadcastReceiver 类:
public class NetConnectionBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
final ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo == null)
Log.v("CONNECT", "NOT CONNECTED");
int netType = networkInfo.getType();
if (netType == ConnectivityManager.TYPE_WIFI)
{
Log.v("CONNECT", "CONNECTED TO WIFI");
}
else if (netType == ConnectivityManager.TYPE_MOBILE)
{
Log.v("CONNECT", "CONNECTED TO MOBILE" +
(networkInfo.isRoaming() ? " ROAMING!" : ""));
}
}
}
您可以将它的实例存储在您的活动中,并且在该onCreate
方法中您可以注册该android.net.conn.CONNECTIVITY_CHANGE
事件:
private final NetConnectionBroadcastReceiver receiver =
new NetConnectionBroadcastReceiver();
public void onCreate(Bundle savedInstanceState)
{
// ... your onCreate implementation goes here
final IntentFilter intentFilter =
new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
this.registerReceiver(this.receiver, intentFilter);
}
当数据连接发生变化时,您会onReceive
调用接收者的方法。你可以从内部检查,发生了什么样的变化。
对于此检查,您只需要android.permission.ACCESS_NETWORK_STATE
权限即可。