当我们进入App的时候,首先会判断当前的网络状态是否可用,如果不可用就弹出一个Dialog让用户进行网络的设置,点击设置的时候跳转到系统的网络设置界面。
运行效果:
网络状态的检查(WangKeUtils.java):
/**
* 检查网络是否可用
* @param context
* @return true,false
*/
public static boolean isNetWorkAvailable(Context context){
ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectManager.getActiveNetworkInfo();
return (info!=null && info.isAvailable());
}
需要注意的是,在检查当前设备的网络状态是否可用的时候需要加上权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
设置界面的跳转:
Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
startActivity(intent);
完整代码:
public class T44Fragment extends Fragment {
private AlertDialog alertDialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_t44, container, false);
if(!WangkeUtils.isNetWorkAvailable(getActivity())){
showSetNetWorkDialog(getActivity());
}
return view;
}
private void showSetNetWorkDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("网络信息提示");
builder.setMessage("当前网络不可用,请先进行设置");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
startActivity(intent);
}
});
builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}