Fully client server application. All data is flying from the backend. How often and where at the start is it better to check for an internet connection? Can I do this when scrolling splashscreen?

public class ActivitySplash extends AppCompatActivity { private static final int SPLASH_TIME = 2000; // delay @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(ActivitySplash.this, MainActivity.class); startActivity(intent); finish(); } }, SPLASH_TIME); } } 

The check itself looks like this for now:

 private void checkNetwork(){ new Thread(new Runnable() { @Override public void run() { if( isInternetAvailable() && isDataServerAvailable()){ finish(); }else{ throwError(); } } }); } private void throwError() { new AlertDialog.Builder(this) .setMessage(R.string.no_internet) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } public boolean isInternetAvailable() { try { InetAddress ipAddr = InetAddress.getByName("google.com"); return !ipAddr.equals(""); } catch (Exception e) { Log.d("INTERNET", "NO INTERNET CONNECTION"); return false; } } public boolean isDataServerAvailable() { try { InetAddress ipAddr = InetAddress.getByName(Constants.BASE_URL); return !ipAddr.equals(""); } catch (Exception e) { Log.d("INTERNET", "DATA SERVER IS DOWN"); return false; } } 
  • It is more logical to do the check in a Thread and, especially, in an Activity . If you are not familiar yet, read about MVP. When I need to do a connection check (or something else) - I create a separate Activity for checks, which contains all the logic in Presenter . If the very first “working” Activity can work without the data that the Activity "для проверок" checks Activity "для проверок" , then I inherit this Activity from the Activity "для проверок" and everything is checked at startup. Otherwise, I first launch the Activity "для проверок" . Of course, this is all accompanied by beautiful ProgressBar 's :). - Rostislav Dugin

3 answers 3

Make a check before you connect

    Do it in catch when the ekpepshen crashes when sending your request. And you don’t need to do it in advance - the code complicates, but there’s little point, it’s especially funny to check whether your smartphone is connected to your router (or a tower close to you ), as if this is something guaranteed :)

    PS I have experience with TCP, not to mention HTTP.

      The check must be done in the IntentService , to which the check of the network must be made. He will tell you about the test results via Broadcast

      When you need to check, call the service and check the result in BroadcastReceiver