Android regular check for internet connection

前端 未结 3 1291
[愿得一人]
[愿得一人] 2021-01-14 23:15

I\'m running an android app that displays a webview on specific URL, I want to check if the application server I\'m accessing is alive and that I can view HTML, if failed I

3条回答
  •  失恋的感觉
    2021-01-14 23:24

    The best way is to use an AsyncTask so your app doesn't freezes.

    private class checkServer extends AsyncTask {
    
            @Override
            protected Void doInBackground(Integer... params) {
                questionRunning = true;
    
                //check if server is running
    
                //now wait 10.000ms (10sec) 
                try {
                    Thread.sleep(params[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                return null;
            }
    
            @Override
            protected void onPostExecute(Void result) {
                // Update your layout here
                super.onPostExecute(result);
    
                //Do it again!
                new checkServer().execute(10000);
    
            }
    
            @Override
            protected void onProgressUpdate(Integer... progress) {
    
            }
        }
    

    How to call your AsynTask:

    new checkServer().execute(10000);
    

提交回复
热议问题