问题
I developing an application which connects to the server. Therefore i want use the bellow function to check if the server is available , But I don't know how I can use it in a thread and how call it each time when I need check if the server is available in activity or fragment :
static public boolean isURLReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://192.168.1.13"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
回答1:
Take a look at this code:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
MyTask task = new MyTask();
task.execute();
}
}
private class MyTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
}
@Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://192.168.1.13"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "server is available", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "server is not available", Toast.LENGTH_SHORT).show();
}
}
}
}
回答2:
You can use just AsyncTask (http://developer.android.com/guide/components/processes-and-threads.html)
Its the android way to run short asynchronous tasks in background, And it has a callback method when finished
来源:https://stackoverflow.com/questions/28856106/check-if-the-server-is-available