Thursday, February 21, 2019

Android check internet connection

We need to check internet connection before open new activity play video online.
First, add this lines to AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Copy to below findViewById.
final ConnectivityManager
cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Last, in the button open next activity, use if command.
NetworkInfo nf=cn.getActiveNetworkInfo();
      if (nf == null){
     Toast.makeText(MainActivity.this,"No internet connection!",
Toast.LENGTH_SHORT).show();                  
     }
      else if (!nf.isConnected()){
     Toast.makeText(MainActivity.this,"No internet connection!", Toast.LENGTH_SHORT).show();
     }
      else if (!nf.isAvailable()){
     Toast.makeText(MainActivity.this,"No internet connection!", Toast.LENGTH_SHORT).show();
     }
      else{
          //start new activity

     }             

No comments:

Post a Comment