相应几乎没有不跟网络打交道的android应用,那么在实际中就需求检测手机是否有网络连接,甚至需要判断是何种方式连接,这样能给用户带来更好的体验和一些使用指导,下面给出一些常用的判断,如果要知道是否有网络、以及是采用wifi连接的还是3G连接的,调用下面对应方法模型就OK了,代码如下:
TestNetworkActivity:
布局xml:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/main_btn_check"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="检测网络" />
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="网络是否连接:" />
-
- <EditText
- android:id="@+id/main_et_net"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:enabled="false" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="wifi是否连接:" />
-
- <EditText
- android:id="@+id/main_et_wifi"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:enabled="false" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="3G是否连接:" />
-
- <EditText
- android:id="@+id/main_et_3g"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:enabled="false" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="GPS是否打开:" />
-
- <EditText
- android:id="@+id/main_et_GPS"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dp"
- android:enabled="false" />
- </LinearLayout>
-
- </LinearLayout>
记得加上相应权限~
附上图片结果:

android中检测网络连接状态简单总结,布布扣,bubuko.com
android中检测网络连接状态简单总结
原文:http://www.cnblogs.com/zhuzhengwen1983/p/3617953.html