我正在尝试执行检查互联网的任务,然后使用连接管理器使用alertdialog警告用户..当我的按钮被按下(单独)时,是否有人知道如何在我的主要活动中实现这一点?
public class MainActivity extends Activity implements OnClickListener {
Button login, register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_bt);
register = (Button) findViewById(R.id.register_bt);
login.setOnClickListener(this);
register.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent i = null;
if (v.getId() == login.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
} else if (v.getId() == register.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
答案 0 :(得分:0)
创建新课程CustomClickListener
:
class CustomClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
if(isOnline()) {
Intent i = null;
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
在OnCreate
方法中:
login.setOnClickListener(new CustomClickListener());
register.setOnClickListener(new CustomClickListener());
此方法检查Internet连接:
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
答案 1 :(得分:0)
检查互联网连接
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
boolean connected=ni != null && ni.getState() == NetworkInfo.State.CONNECTED;
if(connected){
//network connected
}else{
//network disconnected
}
清单
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />