判断网络状态:
public class NetworkChangeReceiver extends BroadcastReceiver {
private String TAG = "NetworkChangeReceiver";
@Override
public void onReceive(Context context, Intent intent) {
State wifiState = null;
State mobileState = null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// 手机没有任何的网络
if (wifiState != null && mobileState != null
&& State.CONNECTED != wifiState
&& State.CONNECTED != mobileState) {
Log.e(TAG,context.getString(R.string.network_error));
} else if (wifiState != null && State.CONNECTED == wifiState) {
// 无线网络连接成功
MainControl.login("bridge1", "123456", "BaytrailD2EC608B");
} else if (wifiState != null && mobileState != null
&& State.CONNECTED != wifiState
&& State.CONNECTED == mobileState) {
// 手机网络连接成功
MainControl.login("bridge1", "123456", "BaytrailD2EC608B");
}
}
}
manifest.xml:
<receiver android:name="com.etb.launcher.NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>