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()
}