Android 如何从onActivityResult启动新活动或任务
我正在尝试使用VoiceRecognition示例向internet机器人发送语音识别文本。所有我需要的是发送信息到一个网址,并获得html代码。 我在ActivityResult中尝试启动httpclient时发现一个问题,我不知道如何解决它。 代码如下:Android 如何从onActivityResult启动新活动或任务,android,android-activity,voice-recognition,Android,Android Activity,Voice Recognition,我正在尝试使用VoiceRecognition示例向internet机器人发送语音识别文本。所有我需要的是发送信息到一个网址,并获得html代码。 我在ActivityResult中尝试启动httpclient时发现一个问题,我不知道如何解决它。 代码如下: public class BkVRMobileActivity extends Activity { private static final int REQUEST_CODE = 1234; private ListVi
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;
公共类BkVRMobileActivity扩展活动
{
私有静态最终整数请求_代码=1234;
私有列表视图单词列表;
私有文本视图texto1;
私有文本视图文本2;
/**
*首先创建使用活动调用的。
*/
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(右布局、语音记录);
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);
//如果没有识别服务,则禁用按钮
PackageManager pm=getPackageManager();
列出活动=pm.querytentActivities(
新意图(识别者意图、行动、识别、言语),0);
如果(activities.size()==0)
{
speakButton.setEnabled(假);
}
}
/**
*处理正在单击的按钮的操作
*/
公共无效speakButtonClicked(视图五)
{
startVoiceRecognitionActivity();
System.out.println(“--al-lio-->”);
}
/**
*激发启动语音识别活动的意图。
*/
私有void startVoiceRecognitionActivity()
{
意向意向=新意向(识别意向、行动、识别言语);
intent.putExtra(识别器intent.EXTRA_语言_模型,
识别者意图、语言、模型、自由形式);
intent.putExtra(RecognizerIntent.EXTRA_提示符,“Reconocimiento de Voz activado…”);
intent.putExtra(识别器intent.EXTRA_MAX_结果,1);
startActivityForResult(意图、请求代码);
}
/**
*处理语音识别活动的结果。
*/
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据)
{
if(requestCode==REQUEST\u CODE&&resultCode==RESULT\u OK)
{
ArrayList matches=data.getStringArrayListExtra(
识别者意图。额外结果);
//setAdapter(新的ArrayAdapter(这个,android.R.layout.simple_list_item_1,matches));
texto1.setText(matches.get(0));
字符串laurl=”http://www.pandorabots.com/pandora/talk-xml?input=“+匹配项。获取(0)+”&botid=9cd68de58e342fb8”;
//使用httpclient打开url以读取html源代码
getXML(laurl);
//系统输出打印LN(laurl);
}
//super.onActivityResult(请求代码、结果代码、数据);
}
公共字符串getXML(字符串url){
字符串log=null;
试一试{
HttpClient HttpClient=new DefaultHttpClient();//创建HTTP客户端
HttpGet HttpGet=newhttpget(url);//设置要执行的操作
HttpResponse response=httpclient.execute(httpget);//Executeit
HttpEntity=response.getEntity();
InputStream is=entity.getContent();//使用响应创建InputStream
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
while((line=reader.readLine())!=null)//逐行读取
sb.追加(第+行“\n”);
字符串resString=sb.toString();//结果在这里
is.close();//关闭流
texto2.setText(resString);
}捕获(不支持的编码异常e){
log=“无法连接到服务器”;
}捕获(格式错误){
log=“无法连接到服务器”;
}捕获(IOE异常){
log=“无法连接到服务器”;
}
返回日志;
}
}
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);
}
公共字符串getXML(字符串url){
新建异步任务(){
私有字符串doInBackgroundThread(字符串…参数)
{
试一试{
HttpClient HttpClient=new DefaultHttpClient();//创建HTTP客户端
HttpGet HttpGet=新建HttpGet(参数[0]);//设置要执行的操作
HttpResponse response=httpclient.execute(httpget);//Executeit
HttpEntity=response.getEntity();
InputStream is=entity.getContent();//使用响应创建InputStream
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
while((line=reader.readLine())!=null)//逐行读取
sb.追加(第+行“\n”);
字符串resString=sb.toString();//结果在这里
is.close();//关闭流
返回字符串;
}捕获(不支持的编码异常e){
}捕获(格式错误){
}捕获(IOE异常){
}
}
@凌驾
受保护的void onPostExecute(字符串结果)
{
texto2.setText(结果);
}
}.执行(url);
}
我得到了这个错误:/AndroidRuntime(10618):java.lang.RuntimeException:未能将结果ResultInfo{who=null,request=1234,result=-1,data=Intent{(has extras)}}传递到活动{prototipos.gneis.bk/prototipos.gneis.bk.BkVRMobileActivity}:android.os.networkonMainthreadExceptionTanks最后我做了类似的事情。一个新的线程就是解决方案
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);
}