您的位置:首页 > 理论基础 > 计算机网络

Android判断网络连接状态并进入网络设置页面

2017-06-09 16:49 477 查看

Android开发中如果要与远程服务器连接,少不了要判断本地设备的联网状态,根据相应的状态提示用户是否进行网络连接。

connectManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
wificonnstate = connectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
mobileconnstate = connectManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
if(wificonnstate != null && mobileconnstate != null
&& wificonnstate == NetworkInfo.State.CONNECTED
&& mobileconnstate != NetworkInfo.State.CONNECTED){
//wifi连接了
Toast.makeText(MainActivity.this, "wifi", Toast.LENGTH_SHORT).show();
}else if(wificonnstate != null && mobileconnstate != null
&& wificonnstate != NetworkInfo.State.CONNECTED
&& mobileconnstate == NetworkInfo.State.CONNECTED){
//移动网络打开了
Toast.makeText(MainActivity.this, "mobile", Toast.LENGTH_SHORT).show();
}else{
//无连接
Toast.makeText(MainActivity.this, "non", Toast.LENGTH_SHORT).show();
//无连接状态提示联网提示框
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("网络连接");
builder.setMessage("网络没有连接是否连接网络?");
builder.setPositiveButton("开启移动网络", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent =  new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
startActivity(intent);
}
});
builder.setNeutralButton("开启wifi", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent =  new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
});
builder.create().show();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android