我正在运行一个在特定 URL 上显示 webview 的 android 应用程序,我想检查我正在访问的应用程序服务器是否处于活动状态并且我可以查看 HTML,如果失败我应该终止 webview,这个检查应该是每 10秒(或其他),最好的方法是什么?
问问题
2102 次
3 回答
2
创建计时器(这里有信息),当计时器滴答时,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 :连接处于活动状态。其他不活跃。
于 2013-01-06T13:50:19.873 回答
1
最好的方法是使用 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);
于 2013-01-06T13:52:03.477 回答
1
使用-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.
要接收互联网连接断开/上升,请侦听“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;
}
}
希望它可以在某个地方对您有所帮助!
于 2013-01-06T14:10:44.563 回答