繁体   English   中英

Android定期检查互联网连接

[英]Android regular check for internet connection

我正在运行一个显示特定URL上的Webview的android应用,我想检查我正在访问的应用服务器是否处于活动状态,并且可以查看HTML,如果失败,则应终止该webview,此检查应为每10次秒(或其他时间),最佳方法是什么?

创建计时器(这里有信息) ,当计时器勾选时,对任何主机执行ping操作:

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

如果返回true:连接处于活动状态。 其他不活跃。

最好的方法是使用AsyncTask,这样您的应用程序就不会冻结。

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

        }
    }

如何调用您的AsynTask:

new checkServer().execute(10000);

使用BroadCastReceiver-Way-高效实现且逼真

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.

要接收已断开/接通的Internet连接,请监听“ ConnectivityManager.CONNECTIVITY_ACTION”操作。

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

每当连接发生变化时(即数据连接已断开或断开),您都会以广播形式接收此事件,因此在接收广播接收器时,请检查Internetconnect连接并确定Internet处于打开还是关闭状态。

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

希望它可以对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM