diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a66882f..0a67958 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,13 +1,16 @@ - + + + + + @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); @@ -74,6 +91,15 @@ public class MainActivity extends Activity { ArrayList result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); txtSpeechInput.setText(result.get(0)); + + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + if (networkInfo != null && networkInfo.isConnected()) { + new TalkToMeTask().execute(result.get(0)); + } else { + txtSpeechInput.setText("No network connection available."); + } } break; } @@ -88,4 +114,65 @@ public class MainActivity extends Activity { return true; } + private class TalkToMeTask extends AsyncTask{ + + @Override + protected String doInBackground(String... question) { + try { + return talkToServer(question[0]); + } catch (IOException e){ + Log.d(TAG, "Coincoin "+e); + return "Cannot connect to server"; + } + } + + @Override + protected void onPostExecute(String s) { + txtSpeechInput.setText(s); + } + + private String talkToServer(String question) throws IOException { + InputStream is = null; + try { + URL url = new URL(Url); + String urlParameters = "msg="+question; + byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); + int postDataLength = postData.length; + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoOutput( true ); + conn.setInstanceFollowRedirects( false ); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + conn.setRequestProperty("charset", "utf-8"); + conn.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + conn.setUseCaches(false); + DataOutputStream wr = new DataOutputStream( conn.getOutputStream()); + wr.write(postData); + + conn.connect(); + int response = conn.getResponseCode(); + Log.d(TAG, "The response is: " + response); + is = conn.getInputStream(); + + + String contentAsString = readIt(is, MAX_ANSWER_LEN); + return contentAsString; + + } finally { + if (is != null){ + is.close(); + } + } + } + // Reads an InputStream and converts it to a String. + public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { + Reader reader = null; + reader = new InputStreamReader(stream, "UTF-8"); + char[] buffer = new char[len]; + reader.read(buffer); + return new String(buffer); + } + } + + }