See below:
Make a method returning a boolean:
ConnectivityManager connectivityManager; NetworkInfo wifiInfo, mobileInfo; 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; }
Use the above method in the onCreate() Like Like method below:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); boolean con = checkNow(getApplicationContext()); if(con){ Toast.makeText(getApplicationContext(), "Connection Founded", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "Connection Not Founded", Toast.LENGTH_SHORT).show(); } }
When you start the application, you will be prompted to specify "Connection Founded" if an Internet connection is available on your device, otherwise, "Connection Not Founded" will be offered.
source share