Android中如何简单检测网络是否连接
发布网友
发布时间:2022-04-24 22:39
我来回答
共1个回答
热心网友
时间:2023-10-13 18:25
权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
代码:
/*
* 判断网络连接是否已开
*true 已打开 false 未打开
**/
public static boolean isConn(Context context){
boolean bisConnFlag=false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
}
return bisConnFlag;
}
/*没有网络跳转到网络设置页面
* 打开设置网络界面
* */
public static void setNetworkMethod(final Context context){
//提示对话框
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent=null;
//判断手机系统的版本 即API大于10 就是3.0或以上版本
if(Build.VERSION.SDK_INT>10){
intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).show();
}