Android regular check for internet connection

前端 未结 3 1290
[愿得一人]
[愿得一人] 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:19

    Using-BroadCastReceiver-Way-It's Efficient-to-implement&realistic

    As you're saying that you need to check the specific server for alive() or not?. Then it depends upon your choice. But always try to be general.

    To receive for Internet Connectivity dropped / up, listen for 'ConnectivityManager.CONNECTIVITY_ACTION' action.

    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    getApplicationContext().registerReceiver(mNetworkStateIntentReceiver, filter);
    

    Whenever there is a change in connectivity i.e it could be either data connection is connected or disconnected, you will receive this event as broadcast, so in onreceive of the broadcast receiver, please check for internetconnect connection and decide whether internet is up or down.

         BroadcastReceiver mNetworkStateIntentReceiver = new BroadcastReceiver()
         {  
          @Override  
          public void onReceive(Context context, Intent intent) 
           {  
             if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
             {  
    
                 NetworkInfo info = intent.getParcelableExtra(  
                         ConnectivityManager.EXTRA_NETWORK_INFO);  
                 String typeName = info.getTypeName();  
                 String subtypeName = info.getSubtypeName();  
                  System.out.println("Network is up ******** "+typeName+":::"+subtypeName);  
    
                 if( checkInternetConnection()== true )  
                 {  
                        "Decide your code logic here...."  
                  }  
              }  
            }
          }
    
    private boolean checkInternetConnection() 
    {  
     ConnectivityManager conMgr = (ConnectivityManager) mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);  
     // ARE WE CONNECTED TO THE NET  
     if (conMgr.getActiveNetworkInfo() != null  && conMgr.getActiveNetworkInfo().isAvailable()  &&conMgr.getActiveNetworkInfo().isConnected())
      {  
       return true;  
      } 
     else
      {  
         return false;  
      }    
    }
    

    Hope it may helps you somewhere!!

    0 讨论(0)
  • 2021-01-14 23:24

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

    private class checkServer extends AsyncTask<Integer, Integer, Void> {
    
            @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);
    
    0 讨论(0)
  • 2021-01-14 23:31

    Create Timer (here you have information) and when timer tick, ping any host :

     URL url = new URL("http://microsoft.com");
    
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
                urlc.connect();
        if (urlc.getResponseCode() == 200) {
            Main.Log("getResponseCode == 200");
                return new Boolean(true);
        }
        } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
    } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        } 
    

    If return true : connection is active. Else isn't active.

    0 讨论(0)
提交回复
热议问题