Java tutorial
package com.chexiaoya.gaodemapdemo; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.support.annotation.Nullable; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.amap.api.services.help.Inputtips; import com.amap.api.services.help.InputtipsQuery; import com.amap.api.services.help.Tip; import com.baidu.speech.VoiceRecognitionService; import com.chexiaoya.gaodemapdemo.event.AssiGestureEvent; import com.chexiaoya.gaodemapdemo.event.ExitEvent; import com.chexiaoya.gaodemapdemo.event.FinalAdressEvent; import com.chexiaoya.gaodemapdemo.event.NavGestureEvent; import com.chexiaoya.gaodemapdemo.event.ServGestEvent; import com.chexiaoya.gaodemapdemo.event.SetGestureEvent; import com.chexiaoya.gaodemapdemo.event.ShootGestureEvent; import com.chexiaoya.gaodemapdemo.utils.Constant; import com.chexiaoya.gaodemapdemo.utils.ShareedPreferenceUtils; import de.greenrobot.event.EventBus; /** * ??GaoDeMapDemo ?? David 2016/8/5 0005 12:27 */ public class SpeechSearchActivity extends Activity implements TextWatcher, Inputtips.InputtipsListener, RecognitionListener { @BindView(R.id.feed_back) ImageView mFeedBack; @BindView(R.id.search_content) AutoCompleteTextView mResultText; @BindView(R.id.search_bt) Button mSearchBt; @BindView(R.id.speachSearch) Button mSpeachSearch; private String city; private void getDatas() { city = ShareedPreferenceUtils.getCity(this); cityCode = ShareedPreferenceUtils.getCityCode(this); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_activity_layout); ButterKnife.bind(this); speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this, new ComponentName(this, VoiceRecognitionService.class)); speechRecognizer.setRecognitionListener(this); getDatas(); /** ? */ mResultText.addTextChangedListener(this); } private String cityCode; private void showToast(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } private void showToast(int message) { Toast.makeText(this, message + "", Toast.LENGTH_LONG).show(); } /** ?poi? */ private String keyWord = ""; @OnClick({ R.id.feed_back, R.id.search_bt, R.id.speachSearch, R.id.naviViewBtn, R.id.assitanBtn, R.id.serviceBtn, R.id.shootBtn, R.id.settingBtn }) public void onClick(View view) { switch (view.getId()) { case R.id.settingBtn: EventBus.getDefault().post(new SetGestureEvent()); finish(); break; case R.id.shootBtn: EventBus.getDefault().post(new ShootGestureEvent()); finish(); break; case R.id.serviceBtn: EventBus.getDefault().post(new ServGestEvent()); finish(); break; case R.id.assitanBtn: EventBus.getDefault().post(new AssiGestureEvent()); finish(); break; case R.id.naviViewBtn: EventBus.getDefault().post(new NavGestureEvent()); finish(); break; case R.id.feed_back: EventBus.getDefault().post(new ExitEvent()); finish(); break; case R.id.search_bt: keyWord = mResultText.getText().toString().trim(); if (TextUtils.isEmpty(keyWord)) { showToast("?"); return; } /** */ FinalAdressEvent event = new FinalAdressEvent(keyWord); EventBus.getDefault().post(event); finish(); break; case R.id.speachSearch: mResultText.setText(""); /** */ start(); break; } } @Override public void onGetInputtips(List<Tip> tipList, int rCode) { if (rCode == 1000) { List<String> listString = new ArrayList<String>(); for (int i = 0; i < tipList.size(); i++) { listString.add(tipList.get(i).getName()); } ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(this, R.layout.route_inputs, listString); mResultText.setAdapter(aAdapter); aAdapter.notifyDataSetChanged(); } else { showToast(rCode + ""); } } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String newText = s.toString().trim(); if (!TextUtils.isEmpty(newText)) { InputtipsQuery inputquery = new InputtipsQuery(newText, city); Inputtips inputTips = new Inputtips(this, inputquery); inputTips.setInputtipsListener(this); inputTips.requestInputtipsAsyn(); } } @Override public void afterTextChanged(Editable editable) { } @Override public void onReadyForSpeech(Bundle bundle) { status = STATUS_Ready; } @Override public void onBeginningOfSpeech() { status = STATUS_Speaking; } @Override public void onRmsChanged(float v) { } @Override public void onBufferReceived(byte[] bytes) { } @Override public void onEndOfSpeech() { } @Override public void onError(int error) { status = STATUS_None; StringBuilder sb = new StringBuilder(); switch (error) { case SpeechRecognizer.ERROR_AUDIO: sb.append(""); break; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: sb.append(""); break; case SpeechRecognizer.ERROR_CLIENT: sb.append(""); break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: sb.append("???"); break; case SpeechRecognizer.ERROR_NETWORK: sb.append(""); break; case SpeechRecognizer.ERROR_NO_MATCH: sb.append("?"); break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: sb.append(""); break; case SpeechRecognizer.ERROR_SERVER: sb.append("?"); break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: sb.append(""); break; } sb.append(":" + error); showToast(sb.toString()); } @Override public void onResults(Bundle results) { if (results != null) { long end2finish = System.currentTimeMillis() - speechEndTime; status = STATUS_None; ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); String json_res = results.getString("origin_result"); try { // print("origin_result=\n" + new // JSONObject(json_res).toString(4)); } catch (Exception e) { // print("origin_result=[warning: bad json]\n" + json_res); } // btn.setText(""); String strEnd2Finish = ""; if (end2finish < 60 * 1000) { strEnd2Finish = "(waited " + end2finish + "ms)"; } Log.i(TAG, "onResults-----> " + nbest.get(0) + strEnd2Finish); String result = nbest.get(0) + strEnd2Finish; mResultText.setText(result); } } @Override public void onPartialResults(Bundle partialResults) { ArrayList<String> nbest = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); if (nbest.size() > 0) { Log.i(TAG, "onPartialResults----> " + nbest.get(0)); String result = nbest.get(0); mResultText.setText(result); } } private static final String TAG = SpeechSearchActivity.class.getSimpleName(); @Override public void onEvent(int eventType, Bundle params) { switch (eventType) { case EVENT_ERROR: String reason = params.get("reason") + ""; showToast("EVENT_ERROR: " + reason); break; case VoiceRecognitionService.EVENT_ENGINE_SWITCH: int type = params.getInt("engine_type"); showToast("*?" + (type == 0 ? "" : "")); break; } } /** */ private static final int STATUS_None = 0; private static final int STATUS_WaitingReady = 2; private static final int STATUS_Ready = 3; private static final int STATUS_Speaking = 4; private static final int STATUS_Recognition = 5; public static final int REQUEST_UI = 1; private SpeechRecognizer speechRecognizer; private int status = STATUS_None; private long speechEndTime = -1; private static final int EVENT_ERROR = 11; private void start() { Intent intent = new Intent(); bindParams(intent); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); { String args = sp.getString("args", ""); if (null != args) { intent.putExtra("args", args); } } boolean api = sp.getBoolean("api", false); if (api) { speechEndTime = -1; speechRecognizer.startListening(intent); } else { intent.setAction("com.baidu.action.RECOGNIZE_SPEECH"); startActivityForResult(intent, REQUEST_UI); } } public void bindParams(Intent intent) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (sp.getBoolean("tips_sound", true)) { intent.putExtra(Constant.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start); intent.putExtra(Constant.EXTRA_SOUND_END, R.raw.bdspeech_speech_end); intent.putExtra(Constant.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success); intent.putExtra(Constant.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error); intent.putExtra(Constant.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel); } if (sp.contains(Constant.EXTRA_INFILE)) { String tmp = sp.getString(Constant.EXTRA_INFILE, "").replaceAll(",.*", "").trim(); intent.putExtra(Constant.EXTRA_INFILE, tmp); } if (sp.getBoolean(Constant.EXTRA_OUTFILE, false)) { intent.putExtra(Constant.EXTRA_OUTFILE, "sdcard/outfile.pcm"); } if (sp.contains(Constant.EXTRA_SAMPLE)) { String tmp = sp.getString(Constant.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constant.EXTRA_SAMPLE, Integer.parseInt(tmp)); } } if (sp.contains(Constant.EXTRA_LANGUAGE)) { String tmp = sp.getString(Constant.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constant.EXTRA_LANGUAGE, tmp); } } if (sp.contains(Constant.EXTRA_NLU)) { String tmp = sp.getString(Constant.EXTRA_NLU, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constant.EXTRA_NLU, tmp); } } if (sp.contains(Constant.EXTRA_VAD)) { String tmp = sp.getString(Constant.EXTRA_VAD, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constant.EXTRA_VAD, tmp); } } String prop = null; if (sp.contains(Constant.EXTRA_PROP)) { String tmp = sp.getString(Constant.EXTRA_PROP, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constant.EXTRA_PROP, Integer.parseInt(tmp)); prop = tmp; } } // offline asr { intent.putExtra(Constant.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1"); intent.putExtra(Constant.EXTRA_LICENSE_FILE_PATH, "/sdcard/easr/license-tmp-20150530.txt"); if (null != prop) { int propInt = Integer.parseInt(prop); if (propInt == 10060) { intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_Navi"); } else if (propInt == 20000) { intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_InputMethod"); } } intent.putExtra(Constant.EXTRA_OFFLINE_SLOT_DATA, buildTestSlotData()); } } private String buildTestSlotData() { JSONObject slotData = new JSONObject(); JSONArray name = new JSONArray().put("?").put(""); JSONArray song = new JSONArray().put("").put("?"); JSONArray artist = new JSONArray().put("?").put("?"); JSONArray app = new JSONArray().put("").put(""); JSONArray usercommand = new JSONArray().put("?").put(""); try { slotData.put(Constant.EXTRA_OFFLINE_SLOT_NAME, name); slotData.put(Constant.EXTRA_OFFLINE_SLOT_SONG, song); slotData.put(Constant.EXTRA_OFFLINE_SLOT_ARTIST, artist); slotData.put(Constant.EXTRA_OFFLINE_SLOT_APP, app); slotData.put(Constant.EXTRA_OFFLINE_SLOT_USERCOMMAND, usercommand); } catch (JSONException e) { } return slotData.toString(); } @Override protected void onStop() { speechRecognizer.stopListening(); super.onStop(); } @Override protected void onDestroy() { speechRecognizer.cancel(); speechRecognizer.destroy(); super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_UI) { if (resultCode == RESULT_OK) { onResults(data.getExtras()); } } } }