2011-11-16 1 views
0

음성 인식 된 텍스트를 인터넷 봇으로 보내려는 VoiceRecognition 샘플을 사용하려고합니다. URL에 정보를 보내고 html 코드를받는 것만으로 충분합니다. onActivityResult에서 httpclient를 시작하는 중 문제가 발생했습니다. 해결 방법을 모르겠습니다. 에,onActivityResult에서 새 활동이나 작업을 시작하는 방법

public class BkVRMobileActivity extends Activity 
{ 

    private static final int REQUEST_CODE = 1234; 
    private ListView wordsList; 
    private TextView texto1; 
    private TextView texto2; 

    /** 
    * Called with the activity is first created. 
    */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.voice_recog); 

    ImageButton speakButton = (ImageButton) findViewById(R.id.speakButton); 
    wordsList = (ListView) findViewById(R.id.list); 
    texto1 = (TextView) findViewById(R.id.textView1); 
    texto2 = (TextView) findViewById(R.id.textView2); 

    // Disable button if no recognition service is present 
    PackageManager pm = getPackageManager(); 
    List<ResolveInfo> activities = pm.queryIntentActivities(
      new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); 
    if (activities.size() == 0) 
    { 
     speakButton.setEnabled(false); 
    } 

} 

/** 
* Handle the action of the button being clicked 
*/ 
public void speakButtonClicked(View v) 
{ 
    startVoiceRecognitionActivity(); 
    System.out.println("--al lio --"); 
    } 

/** 
* Fire an intent to start the voice recognition activity. 
*/ 
private void startVoiceRecognitionActivity() 
{ 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Reconocimiento de Voz activado..."); 
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); 
    startActivityForResult(intent, REQUEST_CODE); 
} 

/** 
* Handle the results from the voice recognition activity. 
*/ 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) 

    { 
     ArrayList<String> matches = data.getStringArrayListExtra(
     RecognizerIntent.EXTRA_RESULTS); 
     //wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,matches)); 
     texto1.setText(matches.get(0)); 

     String laurl = "http://www.pandorabots.com/pandora/talk-xml?input=" + matches.get(0) + "&botid=9cd68de58e342fb8"; 

     //open the url using httpclient for reading html source 
     getXML(laurl); 

     //System.out.println(laurl); 



     } 

    //super.onActivityResult(requestCode, resultCode, data); 
} 

public String getXML(String url){ 
    String log = null; 
    try { 

     HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
     HttpGet httpget = new HttpGet(url); // Set the action you want to do 
     HttpResponse response = httpclient.execute(httpget); // Executeit 
     HttpEntity entity = response.getEntity(); 
     InputStream is = entity.getContent(); // Create an InputStream with the response 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) // Read line by line 
      sb.append(line + "\n"); 

     String resString = sb.toString(); // Result is here 

     is.close(); // Close the stream 
     texto2.setText(resString); 


    } catch (UnsupportedEncodingException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } catch (MalformedURLException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } catch (IOException e) { 
     log = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
    } 

    return log; 

}

}

+0

문제는 무엇입니까? –

+0

다음 오류가 발생합니다./AndroidRuntime (10618) : java.lang.RuntimeException : 결과 전달 실패 ResultInfo {who = null, request = 1234, result = -1, data = 의도 {(추가 사항)}} activity {prototipos .gneis.bk/prototipos.gneis.bk.BkVRMobileActivity} : android.os.NetworkOnMainThreadException – user1049156

답변

1
android.os.NetworkOnMainThreadException 

은 GetXML 그것 (시간이 오래 걸릴 수있는) 어떤 네트워크 요청을 마찬가지로 별도의 스레드에서 실행해야합니다 : 이 코드입니다 UI 스레드는 ANR을 발생시킵니다.

public String getXML(String url){ 
    new AsyncTask<String, Void, String>() { 
       private String doInBackgroundThread(String... params) 
       { 
        try { 

         HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
         HttpGet httpget = new HttpGet(params[0]); // Set the action you want to do 
         HttpResponse response = httpclient.execute(httpget); // Executeit 
         HttpEntity entity = response.getEntity(); 
         InputStream is = entity.getContent(); // Create an InputStream with the response 
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
         StringBuilder sb = new StringBuilder(); 
         String line = null; 
         while ((line = reader.readLine()) != null) // Read line by line 
          sb.append(line + "\n"); 

         String resString = sb.toString(); // Result is here 

         is.close(); // Close the stream 
         return resString; 
        } catch (UnsupportedEncodingException e) { 
        } catch (MalformedURLException e) { 
        } catch (IOException e) { 
        } 
       } 

       @Override 
       protected void onPostExecute(String result) 
       { 
        texto2.setText(result); 
       } 
      }.execute(url); 
} 
+0

마침내 나는 그런 것을했습니다. 새로운 실이 해결책이었습니다. – user1049156