Java tutorial
package com.gqp.duoduo.ui.activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.baidu.speech.VoiceRecognitionService; import com.facebook.drawee.view.SimpleDraweeView; import com.gqp.common.adapter.ViewHolderBind; import com.gqp.common.exception.ErrorMessageException; import com.gqp.common.http.HttpRequest; import com.gqp.common.rx.android.schedulers.AndroidSchedulers; import com.gqp.common.rx.bus.RxBus; import com.gqp.duoduo.App; import com.gqp.duoduo.R; import com.gqp.duoduo.base.BaseActivity; import com.gqp.duoduo.base.Constants; import com.gqp.duoduo.custom.view.NumView; import com.gqp.duoduo.database.Goods; import com.gqp.duoduo.model.GoodsList; import com.gqp.duoduo.model.GoodsMoveDetail; import com.gqp.duoduo.model.InventoryList; import com.gqp.duoduo.utils.HttpUrl; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.view.ViewClickEvent; import com.jakewharton.rxbinding.widget.RxTextView; import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.Request; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import rx.Subscriber; import rx.functions.Action1; /** * Created by admin on 2015/10/29. */ public class SearchGoodsForCheckActivity extends BaseActivity implements RecognitionListener { //? private static final int REQUEST_UI = 1; public static final int STATUS_None = 0; public static final int STATUS_WaitingReady = 2; public static final int STATUS_Ready = 3; public static final int STATUS_Speaking = 4; public static final int STATUS_Recognition = 5; private SpeechRecognizer speechRecognizer; private int status = STATUS_None; private long speechEndTime = -1; private static final int EVENT_ERROR = 11; private List<Goods> mList; private TextView searchCommit; private EditText searchText; private TextView search_result_ok; private ImageView search_voice; private LinearLayout search_result_listview; private Map<String, Goods> selectedGoodsEntityMap; private String isBarcode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_goods_for_check_view); mList = new ArrayList<>(); selectedGoodsEntityMap = new HashMap<>(); isBarcode = getIntent().getStringExtra("isBarcode"); searchText = (EditText) findViewById(R.id.search_edittext); searchCommit = (TextView) findViewById(R.id.search_commit); search_result_ok = (TextView) findViewById(R.id.search_result_ok); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().remove(Constants.EXTRA_INFILE).commit(); // infile?PCM????? speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this, new ComponentName(this, VoiceRecognitionService.class)); speechRecognizer.setRecognitionListener(this); search_voice = (ImageView) findViewById(R.id.search_voice); search_voice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSearch(); } }); if (!TextUtils.isEmpty(isBarcode)) { searchText.setText(isBarcode); if (App.getNetState()) { getGoodsList(isBarcode); } else { showToast("??"); } } searchCommit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String input = searchText.getText().toString(); if (App.getNetState()) { getGoodsList(input); } else { showToast("??"); } } }); search_result_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RxBus.getDefault().send(new Event.SelectFinish(selectedGoodsEntityMap)); SearchGoodsForCheckActivity.this.finish(); } }); search_result_listview = (LinearLayout) findViewById(R.id.search_result_listview); compositeSubscription .add(RxView.clickEvents(findViewById(R.id.search_back)).subscribe(new Action1<ViewClickEvent>() { @Override public void call(ViewClickEvent viewClickEvent) { finish(); } })); compositeSubscription.add(RxTextView.textChangeEvents((EditText) findViewById(R.id.search_edittext)) .throttleLast(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<TextViewTextChangeEvent>() { @Override public void call(TextViewTextChangeEvent textViewTextChangeEvent) { String input = textViewTextChangeEvent.text().toString(); if (App.getNetState()) { getGoodsList(input); } else { showToast("??"); } } }) ); } private void getGoodsList(String input) { if (TextUtils.isEmpty(input)) { return; } showLoading("..."); FormEncodingBuilder builder = new FormEncodingBuilder().add("page", "0").add("size", "65535"); if (!TextUtils.isEmpty(isBarcode)) { builder.add("barcode", input); builder.add("goodsname", ""); } else { builder.add("goodsname", input); } Request request = new Request.Builder().url(HttpUrl.QUERY_GOODS).post(builder.build()) .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID())) .tag(System.currentTimeMillis()).build(); compositeSubscription .add(HttpRequest.modelRequest(request, GoodsList.class).subscribe(new Subscriber<GoodsList>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { // showToast(""); dismissLoading(); if (e instanceof ErrorMessageException) { if (App.getNetState()) { reLogin(); } else { showToast("??"); } } showToast(e.getMessage()); } @Override public void onNext(GoodsList inventoryList) { dismissLoading(); mList.clear(); int size = inventoryList.getRows().size(); search_result_listview.removeAllViews(); mList.addAll(inventoryList.getRows()); if (mList != null && mList.size() > 0) { LayoutInflater inflater = LayoutInflater.from(SearchGoodsForCheckActivity.this); int index = 0; for (Goods entity : mList) { View view = inflater.inflate(R.layout.search_goods_for_check_item, null); SearchGoodsViewItemHolder holder = new SearchGoodsViewItemHolder(view); holder.bind(entity, index); search_result_listview.addView(view); View divider = new View(SearchGoodsForCheckActivity.this); divider.setLayoutParams( new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2)); divider.setBackgroundColor(Color.parseColor("#dddddd")); search_result_listview.addView(divider); index++; } } } })); } public class SearchGoodsViewItemHolder extends ViewHolderBind<Goods> { SimpleDraweeView draweeView; TextView nameTextView; TextView priceTextView; TextView bigPriceTextView; NumView bigNumView; NumView numView; TextView bigUnit; TextView unit; TextView status; LinearLayout layout; Goods entity; public SearchGoodsViewItemHolder(View view) { super(view); draweeView = (SimpleDraweeView) view.findViewById(R.id.goods_check_item_icon); nameTextView = (TextView) view.findViewById(R.id.goods_check_item_name); priceTextView = (TextView) view.findViewById(R.id.goods_check_item_price); bigPriceTextView = (TextView) view.findViewById(R.id.goods_check_item_big_price); bigNumView = (NumView) view.findViewById(R.id.goods_check_item_big_numview); numView = (NumView) view.findViewById(R.id.goods_check_item_numview); bigUnit = (TextView) view.findViewById(R.id.goods_check_item_big_unit); unit = (TextView) view.findViewById(R.id.goods_check_item_unit); } @Override public void bind(Goods data, int pos) { this.entity = data; if (!TextUtils.isEmpty(data.getImagpath())) { draweeView.setImageURI(Uri.parse(data.getImagpath())); } nameTextView.setText(data.getGoodsname() + " 1*" + data.getChangeunit()); priceTextView.setText(data.getItemprice() + "/" + data.getUnit()); bigPriceTextView.setText(data.getBigitemprice() + "/" + data.getBigunit()); bigUnit.setText(data.getBigunit()); unit.setText(data.getUnit()); if (selectedGoodsEntityMap != null && selectedGoodsEntityMap.containsKey(data.getGoodscode())) { bigNumView.setNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceBigNum()); numView.setNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceNum()); data.setChoiceNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceNum()); data.setChoiceBigNum(selectedGoodsEntityMap.get(data.getGoodscode()).getChoiceBigNum()); } TextWatcher tw02 = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { int num = entity.getChoiceBigNum(); try { num = Integer.parseInt(charSequence.toString()); } catch (Exception e) { num = 0; } entity.setChoiceBigNum(num); selectedGoodsEntityMap.put(entity.getGoodscode(), entity); } @Override public void afterTextChanged(Editable editable) { } }; TextWatcher tw01 = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { int num = entity.getChoiceNum(); int bigNum = entity.getChoiceBigNum(); try { num = Integer.parseInt(charSequence.toString()); } catch (Exception e) { num = 0; } if (num >= entity.getChangeunit()) { if (entity.getChangeunit() == 0) { showMess(); return; } else { bigNum = entity.getChoiceBigNum() + num / entity.getChangeunit(); } entity.setChoiceBigNum(bigNum); if (entity.getChangeunit() == 0) { showMess(); return; } else { num = num % entity.getChangeunit(); } entity.setChoiceBigNum(bigNum); entity.setChoiceNum(num); numView.setNum(num); bigNumView.setNum(bigNum); } entity.setChoiceNum(num); entity.setChoiceBigNum(bigNum); selectedGoodsEntityMap.put(entity.getGoodscode(), entity); } @Override public void afterTextChanged(Editable editable) { } }; numView.addTextWatcher(tw01); bigNumView.addTextWatcher(tw02); } } public void showMess() { // AlertDialog.Builder?AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(this); // Title //builder.setIcon(R.drawable.ic_launcher); // Title // builder.setTitle(""); // Content?? builder.setMessage("?????0??!"); // PositiveButton //? builder.setNegativeButton("?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Toast.makeText(mContext, "?.." , Toast.LENGTH_SHORT).show(); } }); //? builder.show(); } public static class Event { public static class SelectFinish { public Map<String, Goods> selectMap; public SelectFinish(Map<String, Goods> selectMap) { this.selectMap = selectMap; } public Map<String, Goods> getSelectMap() { return selectMap; } } } public void startSearch() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SearchGoodsForCheckActivity.this); boolean api = sp.getBoolean("api", false); if (api) { switch (status) { case STATUS_None: start(); // searchVoice.setText("?"); status = STATUS_WaitingReady; break; case STATUS_WaitingReady: cancel(); status = STATUS_None; // searchVoice.setText(""); break; case STATUS_Ready: cancel(); status = STATUS_None; // searchVoice.setText(""); break; case STATUS_Speaking: stop(); status = STATUS_Recognition; // searchVoice.setText(""); break; case STATUS_Recognition: cancel(); status = STATUS_None; // searchVoice.setText(""); break; } } else { start(); } } public void bindParams(Intent intent) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (sp.getBoolean("tips_sound", true)) { intent.putExtra(Constants.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start); intent.putExtra(Constants.EXTRA_SOUND_END, R.raw.bdspeech_speech_end); intent.putExtra(Constants.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success); intent.putExtra(Constants.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error); intent.putExtra(Constants.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel); } if (sp.contains(Constants.EXTRA_INFILE)) { String tmp = sp.getString(Constants.EXTRA_INFILE, "").replaceAll(",.*", "").trim(); intent.putExtra(Constants.EXTRA_INFILE, tmp); } if (sp.getBoolean(Constants.EXTRA_OUTFILE, false)) { intent.putExtra(Constants.EXTRA_OUTFILE, "sdcard/outfile.pcm"); } if (sp.contains(Constants.EXTRA_SAMPLE)) { String tmp = sp.getString(Constants.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constants.EXTRA_SAMPLE, Integer.parseInt(tmp)); } } if (sp.contains(Constants.EXTRA_LANGUAGE)) { String tmp = sp.getString(Constants.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constants.EXTRA_LANGUAGE, tmp); } } if (sp.contains(Constants.EXTRA_NLU)) { String tmp = sp.getString(Constants.EXTRA_NLU, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constants.EXTRA_NLU, tmp); } } if (sp.contains(Constants.EXTRA_VAD)) { String tmp = sp.getString(Constants.EXTRA_VAD, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constants.EXTRA_VAD, tmp); } } String prop = null; if (sp.contains(Constants.EXTRA_PROP)) { String tmp = sp.getString(Constants.EXTRA_PROP, "").replaceAll(",.*", "").trim(); if (null != tmp && !"".equals(tmp)) { intent.putExtra(Constants.EXTRA_PROP, Integer.parseInt(tmp)); prop = tmp; } } // offline asr { intent.putExtra(Constants.EXTRA_OFFLINE_ASR_BASE_FILE_PATH, "/sdcard/easr/s_1"); intent.putExtra(Constants.EXTRA_LICENSE_FILE_PATH, "/sdcard/easr/license-tmp-20150530.txt"); if (null != prop) { int propInt = Integer.parseInt(prop); if (propInt == 10060) { intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_Navi"); } else if (propInt == 20000) { intent.putExtra(Constants.EXTRA_OFFLINE_LM_RES_FILE_PATH, "/sdcard/easr/s_2_InputMethod"); } } intent.putExtra(Constants.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(Constants.EXTRA_OFFLINE_SLOT_NAME, name); slotData.put(Constants.EXTRA_OFFLINE_SLOT_SONG, song); slotData.put(Constants.EXTRA_OFFLINE_SLOT_ARTIST, artist); slotData.put(Constants.EXTRA_OFFLINE_SLOT_APP, app); slotData.put(Constants.EXTRA_OFFLINE_SLOT_USERCOMMAND, usercommand); } catch (JSONException e) { } return slotData.toString(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { onResults(data.getExtras()); } } private void start() { // txtLog.setText(""); // print("?"); Intent intent = new Intent(); bindParams(intent); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); { String args = sp.getString("args", ""); if (null != args) { // print("?" + 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); } // txtResult.setText(""); } private void stop() { speechRecognizer.stopListening(); // print("?"); } private void cancel() { speechRecognizer.cancel(); status = STATUS_None; // print("??"); } @Override public void onReadyForSpeech(Bundle params) { status = STATUS_Ready; // print("??"); } @Override public void onBeginningOfSpeech() { status = STATUS_Speaking; // searchVoice.setText(""); // print("??"); } @Override public void onRmsChanged(float rmsdB) { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { speechEndTime = System.currentTimeMillis(); status = STATUS_Recognition; // print("???"); // searchVoice.setText(""); } @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); // print("" + sb.toString()); // searchVoice.setText(""); } @Override public void onResults(Bundle results) { long end2finish = System.currentTimeMillis() - speechEndTime; status = STATUS_None; ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); // print("?" + Arrays.toString(nbest.toArray(new_version String[nbest.size()]))); System.out.println("" + nbest.get(0)); // String json_res = results.getString("origin_result"); // try { // print("origin_result=\n" + new_version JSONObject(json_res).toString(4)); // } catch (Exception e) { // print("origin_result=[warning: bad json]\n" + json_res); // } if (nbest != null && nbest.size() > 0) { getGoodsList(nbest.get(0)); } else { showToast("?"); } // searchVoice.setText(""); String strEnd2Finish = ""; if (end2finish < 60 * 1000) { strEnd2Finish = "(waited " + end2finish + "ms)"; } } @Override public void onPartialResults(Bundle partialResults) { ArrayList<String> nbest = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); if (nbest.size() > 0) { // print("~" + Arrays.toString(nbest.toArray(new_version String[0]))); } } @Override public void onEvent(int eventType, Bundle params) { switch (eventType) { case EVENT_ERROR: String reason = params.get("reason") + ""; // print("EVENT_ERROR, " + reason); break; case VoiceRecognitionService.EVENT_ENGINE_SWITCH: int type = params.getInt("engine_type"); // print("*?" + (type == 0 ? "" : "")); break; } } @Override protected void onDestroy() { super.onDestroy(); if (compositeSubscription != null) { if (!compositeSubscription.isUnsubscribed()) { compositeSubscription.unsubscribe(); } compositeSubscription = null; } } }