public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void click(View view) {
if(isConn()){
Toast.makeText(this, "网络可用", 0).show();
}else{
Toast.makeText(this, "网络不可用", 0).show();
setNetworkMethod();
}
}
private boolean isConn() {
boolean flag = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = cm.getActiveNetworkInfo();
if (network != null) {
flag = network.isAvailable();
}
return flag;
}
private void setNetworkMethod(){
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("网络设置提示");
builder.setMessage("网络连接不可用,是否进行设置?");
builder.setPositiveButton("设置", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
//判断手机系统的版本 即API大于10 就是3.0或以上版本
if(android.os.Build.VERSION.SDK_INT>10){
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings","com.android.settings.WirelessSettings");
}
startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
}
需要添加一个权限:android.permission.ACCESS_NETWORK_STATE