Search code examples
androidnetwork-programmingwifi3g

How to use any Internet connection in Android app (wifi, 3g, 4g, etc)?


I am writing an app that requires using the Internet. Some relevant bits of code that I have are:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

and

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

However, my app only seems to work on a WiFi connection. How do I make it work regardless of how it connects to the Internet?


Solution

  • try this

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

    and in the Activity that u want to test connection write this code

     NetWorkCheck networkCheck = new NetWorkCheck();
     boolean connection;
    
    connection = networkCheck.checkNow(UpdateVehicleDetails.this);
                    if (connection) {