I wrote the following method to know the reachable of url.
public boolean isMyURLReachable(String url){
boolean reachable = false;
try {
reachable = InetAddress.getByName(url).isReachable(2000);
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return reachable;
}
and I call it like that.
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
boolean reachable = isMyURLReachable("www.google.com");
if(reachable)
Toast.makeText(getApplicationContext(), "Reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "Unreachable", 500).show();
}
});
But android.os.NetworkMainThreadException occur, do I need anything to put in my androidmanifest.xml file or my idea is being wrong?
NetworkMainThreadException
is thrown when an application attempts to perform a networking operation on its main thread.
Please try to perform that in an AysncTask
or another thread.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
I wrote the following inner class.
class URLCheckTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... url) {
boolean reachable = false;
try {
reachable = InetAddress.getByName(url[0]).isReachable(7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(reachable)
return "1";
else
return "0";
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("1"))
Toast.makeText(getApplicationContext(), "reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "unreachable", 500).show();
}
}
and call it from onClick() method.
btnSubmit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new URLCheckTask().execute("www.google.com");
}
});
No exception occur this time. But...., the result is not correct even though I can call it from emulator's browser, it always show me unreachable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.