Đây là cách thực hiện.
lớp này kiểm tra cho một kết nối internet hợp lệ:
public class ConnectionStatus {
private Context _context;
public ConnectionStatus(Context context) {
this._context = context;
}
public boolean isConnectionAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
Các phương pháp sau đây sẽ mở bảng điều khiển wi-fi nếu không có kết nối internet hợp lệ:
public void addListenerOnWifiButton() {
Button btnWifi = (Button)findViewById(R.id.btnWifi);
iia = new ConnectionStatus(getApplicationContext());
isConnected = iia.isConnectionAvailable();
if (!isConnected) {
btnWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
Toast.makeText(getBaseContext(), "Please connect to a hotspot",
Toast.LENGTH_SHORT).show();
}
});
}
else {
btnWifi.setVisibility(4);
warning.setText("This app may use your mobile data to update events and get their details.");
}
}
Các phương pháp sau đây sẽ mở ra 3G bảng điều khiển nếu không có kết nối internet hợp lệ:
public void addListenerOn3GButton() {
Button btnThreeGee = (Button)findViewById(R.id.btn3G);
iia = new ConnectionStatus(getApplicationContext());
isConnected = iia.isConnectionAvailable();
if (!isConnected) {
btnThreeGee.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
Toast.makeText(getBaseContext(), "Please check 'Data enabled' option",
Toast.LENGTH_SHORT).show();
}
});
}
else {
btnThreeGee.setVisibility(4);
cont.setVisibility(View.VISIBLE);
warning.setText("This app may use your mobile data to update events and get their details.");
}
}
Hy vọng điều này sẽ giúp :)
Nguồn
2014-09-05 12:37:00
Đơn giản như vậy, chỉ cần kiểm tra xem có kết nối mạng đang hoạt động hay không. Nếu không, hãy hiển thị yes | no Dialog. Nếu dương, thì hãy hiển thị cài đặt Mạng. Khác, kết thúc hoạt động. –