尝试做这样的:
public static void isNetworkAvailable(final Handler handler, final int timeout)
{
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in
// milliseconds)
new Thread()
{
private boolean responded = false;
@Override
public void run()
{
// set 'responded' to TRUE if is able to connect with google
// mobile (responds fast)
new Thread()
{
@Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest); // can
// last...
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < timeout))
{
sleep(100);
if (!responded)
{
waited += 100;
}
}
}
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
}
else
{ // code if connected
}
}
};
而在你的活动,把它像:
isNetworkAvailable(h, 2000);