public classMainActivityextendsAppCompatActivity {
privateButtonbutton;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//寻找控件ID
button= (Button) findViewById(R.id.bu);
button.setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
if(isNetworkConnected(MainActivity.this)) {
Toast.makeText(MainActivity.this,"网络可用",Toast.LENGTH_SHORT).show();
Intent intent=newIntent(MainActivity.this,M2Activity.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder =newAlertDialog.Builder(MainActivity.this)
.setTitle("提示")
.setMessage("当前网络不可用,是否前去设置")
.setPositiveButton("确定", newDialogInterface.OnClickListener() {
@Override
public voidonClick(DialogInterface dialogInterface, inti) {
Intent intent =newIntent("android.settings.WIFI_SETTINGS");
startActivity(intent);
}
})
.setNegativeButton("取消", newDialogInterface.OnClickListener() {
@Override
public voidonClick(DialogInterface dialogInterface, inti) {
dialogInterface.dismiss();
finish();
}
});
builder.create().show();
}
}
});
}
//判断是否有网络
public booleanisNetworkConnected(Context context) {
if(context !=null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if(mNetworkInfo !=null) {
returnmNetworkInfo.isAvailable();
}
}
return false;
}
}