Android的语音命令做httppost [英] android voice command do httppost
问题描述
我得到语音识别的该例子。我加了一些$ C $下一个httppost命令。我想,当我说这个词DOG做出httppost。一切工作正常,但是当我说的一句话狗时,它应该做的我httppost我得到这些错误:
05-25 21:31:24.889:D / AndroidRuntime(15191):关闭虚拟机
05-25 21:31:24.889:W / dalvikvm(15191):主题ID = 1:螺纹退出与未捕获的异常(组= 0x40aab300)
05-25 21:31:24.909:E / AndroidRuntime(15191):致命异常:主要
05-25 21:31:24.909:E / AndroidRuntime(15191):java.lang.RuntimeException的:不提供结果ResultInfo {谁= NULL,请求= 1001,结果= -1,数据= {意向(有临时演员)}}到活动{com.rakesh.voicerecognitionexample / com.rakesh.voicerecognitionexample.VoiceRecognitionActivity}:android.os.NetworkOnMainThreadException
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread.deliverResults(ActivityThread.java:3267)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread.handleSendResult(ActivityThread.java:3310)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread.access $ 1100(ActivityThread.java:142)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1256)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.os.Handler.dispatchMessage(Handler.java:99)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.os.Looper.loop(Looper.java:137)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread.main(ActivityThread.java:4931)
05-25 21:31:24.909:E / AndroidRuntime(15191):在java.lang.reflect.Method.invokeNative(本机方法)
05-25 21:31:24.909:E / AndroidRuntime(15191):在java.lang.reflect.Method.invoke(Method.java:511)
05-25 21:31:24.909:E / AndroidRuntime(15191):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:791)
05-25 21:31:24.909:E / AndroidRuntime(15191):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
05-25 21:31:24.909:E / AndroidRuntime(15191):在dalvik.system.NativeStart.main(本机方法)
05-25 21:31:24.909:E / AndroidRuntime(15191):由:android.os.NetworkOnMainThreadException
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-25 21:31:24.909:E / AndroidRuntime(15191):在java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-25 21:31:24.909:E / AndroidRuntime(15191):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-25 21:31:24.909:E / AndroidRuntime(15191):在java.net.InetAddress.getAllByName(InetAddress.java:214)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-25 21:31:24.909:E / AndroidRuntime(15191):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-25 21:31:24.909:E / AndroidRuntime(15191):在com.rakesh.voicerecognitionexample.VoiceRecognitionActivity.cici(VoiceRecognitionActivity.java:157)
05-25 21:31:24.909:E / AndroidRuntime(15191):在com.rakesh.voicerecognitionexample.VoiceRecognitionActivity.onActivityResult(VoiceRecognitionActivity.java:113)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.Activity.dispatchActivityResult(Activity.java:5192)
05-25 21:31:24.909:E / AndroidRuntime(15191):在android.app.ActivityThread.deliverResults(ActivityThread.java:3263)
05-25 21:31:24.909:E / AndroidRuntime(15191):11 ...更多
下面是我的code:
包com.rakesh.voicerecognitionexample;
进口java.io.IOException异常;
进口的java.util.ArrayList;
进口的java.util.List;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口android.app.Activity;
进口android.app.SearchManager;
进口android.content.Intent;
进口android.content.pm.PackageManager;
进口android.content.pm.ResolveInfo;
进口android.os.Bundle;
进口android.speech.RecognizerIntent;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.ArrayAdapter;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.ListView;
进口android.widget.Spinner;
进口android.widget.Toast;
公共类VoiceRecognitionActivity延伸活动{
私有静态最终诠释VOICE_RECOGNITION_REQUEST_ code = 1001;
私人的EditText metTextHint;
私人的ListView mlvTextMatches;
私人微调msTextMatches;
私人按钮mbtSpeak;
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_voice_recognition);
metTextHint =(EditText上)findViewById(R.id.etTextHint);
mlvTextMatches =(ListView控件)findViewById(R.id.lvTextMatches);
msTextMatches =(微调)findViewById(R.id.sNoOfMatches);
mbtSpeak =(按钮)findViewById(R.id.btSpeak);
}
公共无效checkVoiceRecognition(){
//检查语音识别是present
PackageManager下午= getPackageManager();
名单< ResolveInfo>活动= pm.queryIntentActivities(新意图(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
如果(activities.size()== 0){
mbtSpeak.setEnabled(假);
Toast.makeText(这一点,语音识别不是present
Toast.LENGTH_SHORT).show();
}
}
公共无效说话(查看视图){
意向意图=新的意图(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//指定调用包,以确定您的应用程序
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,的getClass()
。.getPackage()的getName());
//显示一个提示,关于他应该说些什么用户。
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,metTextHint.getText()
的ToString());
//给出一个提示什么用户会说识别器
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
//如果没有选择匹配的编号,然后返回显示敬酒消息
如果(msTextMatches.getSelectedItemPosition()== AdapterView.INVALID_POSITION){
Toast.makeText(这一点,请选择微调匹配的号,
Toast.LENGTH_SHORT).show();
返回;
}
INT noOfMatches =的Integer.parseInt(msTextMatches.getSelectedItem()
的ToString());
//指定你要多少成绩获得。结果将是
//排序,其中的第一个结果是具有较高的信心。
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,noOfMatches);
startActivityForResult(意向,VOICE_RECOGNITION_REQUEST_ code);
}
@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){
如果(要求code == VOICE_RECOGNITION_REQUEST_ code)
//如果语音识别成功,则它返回RESULT_OK
如果(结果code == RESULT_OK){
ArrayList的<字符串> textMatchList =数据
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
如果(!textMatchList.isEmpty()){
//如果第一场比赛中包含了搜索字
//然后启动网络搜索。
如果(textMatchList.get(0)。载(搜索)){
字符串searchQuery = textMatchList.get(0).replace(搜索,
);
搜索意图=新的意图(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY,searchQuery);
startActivity(搜索);
}否则,如果(textMatchList.get(0)。载(狗)){
postTo();
} 其他 {
//填充匹配
mlvTextMatches
.setAdapter(新ArrayAdapter<字符串>(这一点,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//结果code的各种错误。
}否则,如果(结果code == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage(音频错误);
}否则,如果(结果code == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage(客户端错误);
}否则,如果(结果code == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage(网络错误);
}否则,如果(结果code == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage(不匹配);
}否则,如果(结果code == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage(服务器错误);
}
super.onActivityResult(要求code,因此code,数据);
}
无效showToastMessage(字符串消息){
Toast.makeText(此,信息,Toast.LENGTH_SHORT).show();
}
公共无效postTo()
{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(http://mysite.com/script.php);
尝试 {
名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
nameValuePairs.add(新BasicNameValuePair(消息,cracanel));
httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
httpclient.execute(httppost);
}赶上(ClientProtocolException E){
// TODO自动生成的catch块
}赶上(IOException异常E){
// TODO自动生成的catch块
}
}
}
它是一种NetworkOnMainThread例外。你不能在主UI线程上运行的网络相关的操作。您应该使用AsyncTask的用于这一目的。
的http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
有关的AsyncTask
http://developer.android.com/reference/android/os/ AsyncTask.html
您也可以创建自己的线程,并执行httppost。但要确保不要在backgroudn线程更新UI。 Asyntask使你更容易
例如:
类TheTask扩展的AsyncTask<虚空,虚空,虚空>
{
@覆盖
在preExecute保护无效(){
// TODO自动生成方法存根
super.on preExecute();
// UI线程调用。
//显示进度对话框
}
@覆盖
保护无效onPostExecute(无效的结果){
// TODO自动生成方法存根
super.onPostExecute(结果);
//在UI线程调用
//开除进度对话框
// doinbackground计算结果是一个参数,该
//可以在这里更新用户界面
}
@覆盖
保护无效doInBackground(虚空......为arg0){
// TODO自动生成方法存根
//在后台线程调用
//不更新的用户界面
//这里执行HTTP POST
postTo(); //这里调用你的POST方法
返回null;
}
}
用法:
新TheTask()执行()。 //加载UI线程
可以传递参数的AsyncTask的构造。你也可以传递参数直接doinbackground。
I got this example of voice recognition. I added some code for a httppost command. I want, when i say the word DOG to make a httppost. All works fine, but when i say the word DOG and when it's supposed to do my httppost i get these errors:
05-25 21:31:24.889: D/AndroidRuntime(15191): Shutting down VM
05-25 21:31:24.889: W/dalvikvm(15191): threadid=1: thread exiting with uncaught exception (group=0x40aab300)
05-25 21:31:24.909: E/AndroidRuntime(15191): FATAL EXCEPTION: main
05-25 21:31:24.909: E/AndroidRuntime(15191): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1001, result=-1, data=Intent { (has extras) }} to activity {com.rakesh.voicerecognitionexample/com.rakesh.voicerecognitionexample.VoiceRecognitionActivity}: android.os.NetworkOnMainThreadException
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread.deliverResults(ActivityThread.java:3267)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3310)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread.access$1100(ActivityThread.java:142)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.os.Looper.loop(Looper.java:137)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread.main(ActivityThread.java:4931)
05-25 21:31:24.909: E/AndroidRuntime(15191): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 21:31:24.909: E/AndroidRuntime(15191): at java.lang.reflect.Method.invoke(Method.java:511)
05-25 21:31:24.909: E/AndroidRuntime(15191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-25 21:31:24.909: E/AndroidRuntime(15191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
05-25 21:31:24.909: E/AndroidRuntime(15191): at dalvik.system.NativeStart.main(Native Method)
05-25 21:31:24.909: E/AndroidRuntime(15191): Caused by: android.os.NetworkOnMainThreadException
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-25 21:31:24.909: E/AndroidRuntime(15191): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-25 21:31:24.909: E/AndroidRuntime(15191): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-25 21:31:24.909: E/AndroidRuntime(15191): at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-25 21:31:24.909: E/AndroidRuntime(15191): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-25 21:31:24.909: E/AndroidRuntime(15191): at com.rakesh.voicerecognitionexample.VoiceRecognitionActivity.cici(VoiceRecognitionActivity.java:157)
05-25 21:31:24.909: E/AndroidRuntime(15191): at com.rakesh.voicerecognitionexample.VoiceRecognitionActivity.onActivityResult(VoiceRecognitionActivity.java:113)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.Activity.dispatchActivityResult(Activity.java:5192)
05-25 21:31:24.909: E/AndroidRuntime(15191): at android.app.ActivityThread.deliverResults(ActivityThread.java:3263)
05-25 21:31:24.909: E/AndroidRuntime(15191): ... 11 more
Here is my code:
package com.rakesh.voicerecognitionexample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_recognition);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast message
if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery = textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else if (textMatchList.get(0).contains("dog")) {
postTo();
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void postTo()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("message", "cracanel"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Its a NetworkOnMainThread exception. You cannot run network related operation on the main ui thread. You should use asynctask for this purpose.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
For asynctask
http://developer.android.com/reference/android/os/AsyncTask.html
You can also create your own thread and execute httppost. But make sure you don't update ui on the backgroudn thread. Asyntask makes it easier for you
Example:
class TheTask extends AsyncTask<Void,Void,Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// invoked on the ui thread.
// display progress dialog
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//invoked on the ui thread
// dismiss progress dialog
// result of doinbackground computation is a parameter to this
// can update ui here
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//invoked on the background thread
// do not update ui
// execute http post here
postTo(); // call your post method here
return null;
}
}
Usage:
new TheTask().execute(); // load on ui thread
Can pass parameter to the constructor of asynctask. You can also pass parameter to doinbackground directly.
这篇关于Android的语音命令做httppost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!