com.gqp.duoduo.ui.activity.SearchMarketVoiceActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.gqp.duoduo.ui.activity.SearchMarketVoiceActivity.java

Source

package com.gqp.duoduo.ui.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.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.speech.VoiceRecognitionService;
import com.gqp.common.cache.SpCache;
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.adapter.SearchResultAdapter;
import com.gqp.duoduo.base.BaseActivity;
import com.gqp.duoduo.base.Constants;
import com.gqp.duoduo.database.Market;
import com.gqp.duoduo.database.dao.MarketDao;
import com.gqp.duoduo.model.MarketList;
import com.gqp.duoduo.utils.HttpUrl;
import com.gqp.duoduo.utils.SharedPreferencesKey;
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.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Created by admin on 2015/10/19.
 */
public class SearchMarketVoiceActivity 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<Market> mList;
    private SearchResultAdapter adapter;
    private EditText searchText;
    private TextView searchVoice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_view_voice);
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        sp.edit().remove(Constants.EXTRA_INFILE).commit(); // infile?PCM?????
        mList = new ArrayList<>();

        adapter = new SearchResultAdapter(this, mList);
        searchText = (EditText) findViewById(R.id.search_edittext);
        searchVoice = (TextView) findViewById(R.id.search_voice_btn);
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
                new ComponentName(this, VoiceRecognitionService.class));
        speechRecognizer.setRecognitionListener(this);
        startSearch();
        searchVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSearch();
            }
        }); //activity

        ListView listView = (ListView) findViewById(R.id.search_result_listview);
        listView.setAdapter(adapter);

        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()) {
                            getMarketList(input);

                        } else {
                            getLocalData(input);
                        }

                    }
                })

        );

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent send = new Intent(SearchMarketVoiceActivity.this, SendItemActivity.class);

                Market rowsEntity = mList.get(i);

                send.putExtra(Constants.PARAM_MARKET_NAME, rowsEntity.getMarketname());
                send.putExtra(Constants.PARAM_MARKET_CODE, rowsEntity.getMarketcode());
                send.putExtra("xyf", rowsEntity.getXyf());

                SpCache.putString(Constants.CURRENT_MARKET_LOC,
                        rowsEntity.getAddress() == null ? "" : rowsEntity.getAddress());
                SpCache.putString(Constants.CURRENT_MARKET_LINKMAN,
                        rowsEntity.getLinkman() == null ? "" : rowsEntity.getLinkman());
                if (!TextUtils.isEmpty(rowsEntity.getTel()) || !TextUtils.isEmpty(rowsEntity.getPhone())) {
                    if (!TextUtils.isEmpty(rowsEntity.getTel())) {
                        SpCache.putString(Constants.CURRENT_MARKET_TEL,
                                rowsEntity.getTel() == null ? "" : rowsEntity.getTel());
                    } else {
                        SpCache.putString(Constants.CURRENT_MARKET_TEL,
                                rowsEntity.getPhone() == null ? "" : rowsEntity.getPhone());
                    }
                } else {
                    SpCache.putString(Constants.CURRENT_MARKET_TEL,
                            rowsEntity.getTel() == null ? "" : rowsEntity.getTel());
                }
                SpCache.putString(Constants.CURRENT_MARKET_NAME,
                        rowsEntity.getMarketname() == null ? "" : rowsEntity.getMarketname());
                SpCache.putString(Constants.CURRENT_MARKET_CODE,
                        rowsEntity.getMarketcode() == null ? "" : rowsEntity.getMarketcode());
                SpCache.putString(Constants.CURRENT_MARKET_LNG,
                        rowsEntity.getLon() == null ? "0" : rowsEntity.getLon());
                SpCache.putString(Constants.CURRENT_MARKET_LAT,
                        rowsEntity.getDim() == null ? "0" : rowsEntity.getDim());
                SpCache.putString(Constants.CURRENT_MARKET_TYPE_IS_SEE_PRICE, "0");
                startActivity(send);
            }
        });

        Observable<MainActivity.MainActivityEvent.DeliverEvent> deliverEventObservable = RxBus.getDefault()
                .register(MainActivity.MainActivityEvent.DeliverEvent.class);

        compositeSubscription
                .add(deliverEventObservable.subscribe(new Action1<MainActivity.MainActivityEvent.DeliverEvent>() {
                    @Override
                    public void call(MainActivity.MainActivityEvent.DeliverEvent deliverEvent) {

                        finish();
                    }
                }));

    }

    private void getLocalData(String input) {
        if (TextUtils.isEmpty(input)) {
            return;
        }
        List<Market> list = App.getDaoSession(this).getMarketDao().queryBuilder()
                .where(MarketDao.Properties.Marketname.like("%" + input + "%")).limit(10).list();
        mList.clear();

        mList.addAll(list);

        adapter.notifyDataSetChanged();
    }

    private void getMarketList(String input) {

        if (TextUtils.isEmpty(input)) {
            return;
        }

        String loc = SpCache.getString(SharedPreferencesKey.CURRENT_LOC, "");
        String lat = "";
        String lng = "";
        if (!TextUtils.isEmpty(loc)) {

            lat = loc.split(",")[0];
            lng = loc.split(",")[1];

        }

        Request request = new Request.Builder().url(HttpUrl.MARKET_LIST)
                .post(new FormEncodingBuilder().add("page", "0").add("size", "10").add("marketname", input)
                        .add("lons", String.valueOf(lng)).add("dims", String.valueOf(lat)).add("flg", "1")
                        .add("raidus", "5000").build())
                .addHeader("accept", "application/json").addHeader("dodomobile", String.valueOf(UUID.randomUUID()))
                .tag(System.currentTimeMillis()).build();

        compositeSubscription
                .add(HttpRequest.modelRequest(request, MarketList.class).subscribe(new Subscriber<MarketList>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        //                                showToast("");
                        if (e instanceof ErrorMessageException) {
                            if (App.getNetState()) {
                                reLogin();
                            } else {
                                showToast("??");
                            }
                        }
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onNext(MarketList marketList) {

                        int size = marketList.getMessage().getSuperMarketContent().size();

                        mList.clear();

                        mList.addAll(marketList.getMessage().getSuperMarketContent());

                        adapter.notifyDataSetChanged();
                        //                                MarketList.MessageEntity.SuperMarketContentEntity rowsEntity = marketList.getMessage().getSuperMarketContent().get(i);

                    }
                }));
    }

    public void startSearch() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SearchMarketVoiceActivity.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 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) {
            getMarketList(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 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;
        }
    }

    private void print(String msg) {
        System.out.print("out====" + msg);
    }
}