下面解决办法来自于android学习手册,android学习手册包含9个章节,108个例子,源码文档随便看,例子都是可交互,可运行,源码采用android studio目录结构,高亮显示代码,文档都采用文档结构图显示,可以快速定位。360手机助手中下载。排到第三个。
1、获取ConnectivityManager对象
Context context = activity.getApplicationContext()
// 获取手机所有连接管理对象(包团和括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)
2、获取NetworkInfo对象
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo()
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 = 0i <networkInfo.lengthi++)
{
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
}
}
using Systemusing System.Collections.Generic
using System.Text
using Microsoft.VisualBasic.Devices
namespace pro
{
class net
{
static void Main()
{
Computer pc = new Computer()
if (pc.Network.IsAvailable)
{
Console.WriteLine("现山升在网络是通的!")
}
else
{
Console.WriteLine("网伍唯举络腔碧不通!")
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)