如何在Android应用程序中使用任何互联网连接(wifi,3g,4g等)



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

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

试试这个

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) {

相关内容

  • 没有找到相关文章

最新更新