2011-11-16 33 views
0

我試圖使用VoiceRecognition示例將語音識別文本發送到Internet bot。我需要的只是發送信息到一個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 = Intent {(has extras)}} to activity {prototipos .gneis.bk/prototipos.gneis.bk.BkVRMobileActivity}:android.os.NetworkOnMainThreadException – user1049156

回答

1
android.os.NetworkOnMainThreadException 

的getXML需要因爲它的網絡請求(其可能需要很長的時間),其在一個單獨的線程來運行,上UI線程將導致ANRs

類似於:

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