判断网络工具类

进入页面做网络判断,网络未连接跳转到设置网络页面进行设置:
/**
* 检测当前的网络(WLAN3G/2G)状态
* @param context Context
* @return true 表示网络可用
* 清单配置网络权限
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
/**
* 进入页面做网络判断,网络未连接跳转到设置网络页面进行设置
*/
private void getRun() {
if (isNetworkAvailable(this)){
//网络连接成功,加载网络请求的数据
initData();
}else {
//网络未连接跳转到设置网络页面进行设置
setNetwork();
}

}
/**
* 网络未连接时,调用设置方法
导包:
import android.support.v7.app.AlertDialog;
import android.content.DialogInterface;
*/
private void setNetwork(){
Toast.makeText(this), "wifi is closed!", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("网络提示信息");
builder.setMessage("网络不可用,如果继续,请先设置网络!");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
/**
* 判断手机系统的版本!如果API大于10 就是3.0+
* 因为3.0以上的版本的设置和3.0以下的设置不一样,调用的方法不同
*/
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(android.provider.Settings.ACTION_WIFI_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");
}
startActivity(intent);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值