Android判断网络状态的代码
本文实例为大家分享了Android判断网络状态的具体代码,供大家参考,具体内容如下
一、权限
需要在AndroidManifest.xml 添加访问权限
<usespermissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
二、判断连接状态
/**
* 判断是否有网络连接
* @param context
* @return
*/
public static boolean isConnect(Context context) {
boolean _isConnect = false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if (network != null) {
_isConnect = conManager.getActiveNetworkInfo().isAvailable();
}
return _isConnect;
}
三、打开网络设置对话框
/**
* 打开系统网络设置界面
* @param context
*/
public 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;
//3.0之前和之后API不同,需要判断
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(android.provider.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();
}
四、调用
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isConnect(TwoActivity.this)){
setNetworkMethod(TwoActivity.this);
}
}
});
以上是 Android判断网络状态的代码 的全部内容, 来源链接: utcz.com/z/336912.html