本文转载自:http://www.cnblogs.com/renqingping/archive/2012/10/18/Net.html
当前有可用网络,如下图:
当前没有可用网络,如下图:
实现步骤:
1、获取ConnectivityManager对象
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
2、获取NetworkInfo对象
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
3、判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
4、在AndroidManifest.xml中添加访问当前网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
代码如下:
public class ClassTestDemoActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isNetworkAvailable(ClassTestDemoActivity.this))
{
Toast.makeText(getApplicationContext(), "当前有可用网络!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "当前没有可用网络!", Toast.LENGTH_LONG).show();
}
}
/**
* 检查当前网络是否可用
*
* @param context
* @return
*/
public boolean isNetworkAvailable(Activity activity)
{
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
{
return false;
}
else
{
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0)
{
for (int i = 0; i < networkInfo.length; i++)
{
System.out.println(i + "===状态===" + networkInfo[i].getState());
System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}
控制台打印出的结果: