Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to detect whether the android device has Internet connection or not?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 308
    Comment on it

    If your android app is dependent on internet then you need to check whether your device is having internet connection or not at the starting of your app, so to check the same copy the code below :-

    To know the Network state in your app you need to add the permission in your manifest file

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

    Here I have created the method DetectNetwork which returns the boolean value , that will be true if the internet connection is available and false if not.

    MainActivity.java

    public class MainActivity extends AppCompatActivity
     {
        
        private boolean mnetwork;
    
           protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
       
            mnetwork=DetectNetwork();
          
          if(mnetwork)
           {
            Toast.makeText(this,"Network is "+mnetwork,Toast.LENGTH_LONG).show(); 
            // Do something
            }
         }
    
        private boolean DetectNetwork() {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: