in tutorial/android/src/main/java/com/google/bazel/example/android/activities/MainActivity.java [53:123]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_ping) {
new AsyncTask<String, Void, String>() {
public static final int READ_TIMEOUT_MS = 5000;
public static final int CONNECTION_TIMEOUT_MS = 2000;
private String inputStreamToString(InputStream stream) throws IOException {
StringBuilder result = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} finally {
stream.close();
}
return result.toString();
}
private HttpURLConnection getConnection(String url) throws IOException {
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_MS);
urlConnection.setReadTimeout(READ_TIMEOUT_MS);
return (HttpURLConnection) urlConnection;
}
@Override
protected String doInBackground(String... params) {
String url = params[0];
HttpURLConnection connection = null;
try {
connection = getConnection(url);
return new JSONObject(inputStreamToString(connection.getInputStream()))
.getString("requested");
} catch (IOException e) {
Log.e("background", "IOException", e);
return null;
} catch (JSONException e) {
Log.e("background", "JSONException", e);
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
@Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.text_view);
if (result == null) {
Toast.makeText(
MainActivity.this, getString(R.string.error_sending_request), Toast.LENGTH_LONG)
.show();
textView.setText("???");
return;
}
textView.setText(result);
}
}.execute("http://10.0.2.2:8080/boop");
return true;
}
return super.onOptionsItemSelected(item);
}