问题
Below is the piece of Android code which works fine to check if network is connected or not.
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But having an active network interface doesn't guarantee that a particular networked service is available.
A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google
Common scenario:
- Android device connected to a Wi-Fi, which turns out to be a private network. So isNetworkAvailable will return that network is connected, but could not be connected to any other service
- Some times the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access Google/Yahoo.
One way is to check if "isNetworkAvailable" function returns TRUE, then run following code
HttpGet request = new HttpGet(url));
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
}
}
catch (SocketException e)
{
return "Socket Exceptiopn:" + e.toString();
}
catch (Exception e)
{
return "General Execption:" + e.toString();
}
But I think this is not an good way because it may consume lot of time
So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?
回答1:
check this code... it worked for me :)
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();
}
Then, I define the handler:
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Code from Gilbou https://stackoverflow.com/a/5803489/2603719
I hope i can Help you
回答2:
Issue #1:
Android device connected to a Wi-Fi, which turns out to be a private network.
So isNetworkAvailable
will return that network is connected, but could not be connected to any other service.
Issue #2:
Sometimes the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access google/yahoo.
I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.
Ultimately, you will need to Monitor the change in Network connection,
Step 1:
Just register a BroadcastReceiver
for following action
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
Step 2:
when you get callback on onReceive(Context context,Intent intent)
method ,check for connectivity status.
i.e:
boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
//apart from EXTRA_NO_CONNECTIVITY
, there are other parameters also which will be useful to monitor
Reference:
Examples:
Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android
Android-getting-notified-of-connectivity-changes
Github: Example for network-detect-notify
Android Docs:
Connectivity Monitoring
Connectivity Manager
I hope it will be helpful !!
回答3:
Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.
boolean flag=false;
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
flag=true;
}
}
if(flag==true)
{
Log.e("TAG","Internet Is Connected");
}
else
{
Log.e("TAG","Internet Is Not Connected");
}
来源:https://stackoverflow.com/questions/21040146/android-check-network-and-real-internet-connectivity