Android regular check for internet connection

天大地大妈咪最大 提交于 2019-12-01 09:21:28

问题


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 should terminate the webview, this check should be every 10 seconds (or whatever), what is the best approach for this ?


回答1:


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.




回答2:


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);



回答3:


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!!



来源:https://stackoverflow.com/questions/14182708/android-regular-check-for-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!