进入页面做网络判断,网络未连接跳转到设置网络页面进行设置:
/**
*
检测当前的网络(
WLAN
、
3G/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();
}