我正在编写一个需要使用互联网的应用。我拥有的一些相关代码是:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
和
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
// do stuff
return true;
}
else{
// don't do stuff and display dialog instead
return false;
}
}
但是,我的应用似乎只适用于WiFi连接。无论它如何连接到互联网,我该如何使其工作?
答案 0 :(得分:1)
试试这个
public class NetWorkCheck{
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo, lanInfo;
public Boolean checkNow(Context con){
try{
connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifiInfo.isConnected() || mobileInfo.isConnected())
{
return true;
}
}
catch(Exception e){
System.out.println("CheckConnectivity Exception: " + e.getMessage());
}
return false;
}
}
并在您要测试连接的Activity中编写此代码
NetWorkCheck networkCheck = new NetWorkCheck();
boolean connection;
connection = networkCheck.checkNow(UpdateVehicleDetails.this);
if (connection) {