0

我正在编写一个需要使用 Internet 的应用程序。我拥有的一些相关代码是:

<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 连接上运行。无论它如何连接到 Internet,我如何使它工作?

4

1 回答 1

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;
    }
}

并在您要测试连接的活动中编写此代码

 NetWorkCheck networkCheck = new NetWorkCheck();
 boolean connection;

connection = networkCheck.checkNow(UpdateVehicleDetails.this);
                if (connection) {
于 2012-10-10T14:39:46.503 回答