我正在尝试确定我的应用程序是否已连接到互联网。我将超时设置为 3 秒。有时 Internet 检查会以“未连接”的形式返回(即使我确实有 Internet 连接),有时它不会。为什么有时检查比其他人需要更长的时间?在检查时,我可以弹出一个对话框或其他东西吗?
public void isNetworkAvailable(final Handler handler)
{
new Thread()
{
private boolean responded = false;
@Override
public void run()
{
new Thread()
{
@Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest);
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < 3000))
{
sleep(100);
if (!responded)
{
waited += 1000;
}
}
}
catch (InterruptedException e)
{
} // do nothing
finally
{
if (!responded)
{
handler.sendEmptyMessage(0);
}
else
{
handler.sendEmptyMessage(1);
}
}
}
}.start();
}
Handler h = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what != 1)
{ // code if not connected
Log.i("Internet check", "Not connected");
}
else
{ // code if connected
Log.i("Internet check", "Connected");
}
}
};