Example usage for android.speech.tts TextToSpeech TextToSpeech

List of usage examples for android.speech.tts TextToSpeech TextToSpeech

Introduction

In this page you can find the example usage for android.speech.tts TextToSpeech TextToSpeech.

Prototype

public TextToSpeech(Context context, OnInitListener listener) 

Source Link

Document

The constructor for the TextToSpeech class, using the default TTS engine.

Usage

From source file:org.thecongers.mcluster.MainActivity.java

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

    // Keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);//from  w w w  .j  a v  a2s  .  c  om

    View myView = findViewById(R.id.layoutApp);
    root = myView.getRootView();
    layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons);
    layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft);
    layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight);
    layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft);
    layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight);
    imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch);
    imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow);
    imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow);
    imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam);
    imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips);
    imageABS = (ImageView) findViewById(R.id.imageViewABS);
    imageLampf = (ImageView) findViewById(R.id.imageViewLampf);
    imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning);
    imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel);
    imageESA = (ImageView) findViewById(R.id.imageViewESA);
    txtSpeed = (TextView) findViewById(R.id.textViewSpeed);
    txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit);
    txtGear = (TextView) findViewById(R.id.textViewGear);
    txtOdometers = (TextView) findViewById(R.id.textViewOdometer);
    txtESA = (TextView) findViewById(R.id.textViewESA);
    imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS);
    imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth);
    imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference);
    progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel);

    // Backgrounds
    background = R.drawable.rectangle_bordered;
    backgroundDark = R.drawable.rectangle_bordered_dark;

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update layout
    updateLayout();

    if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        imageButtonTPMS.setImageResource(R.mipmap.blank_icon);
        imageButtonTPMS.setEnabled(false);
    } else {
        imageButtonTPMS.setImageResource(R.mipmap.tpms_off);
        imageButtonTPMS.setEnabled(true);
    }

    // Set initial color scheme
    updateColors();
    if (sharedPrefs.getBoolean("prefNightMode", false)) {
        imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
    }

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    // Setup Text To Speech
    text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                text2speech.setLanguage(Locale.US);
            }
        }
    });

    imageButtonBluetooth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            canBusConnect();
        }
    });

    imageButtonTPMS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
                iTPMSConnect();
            }
        }
    });

    imageButtonPreference.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(MainActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_settings:
                        // Settings Menu was selected
                        Intent i = new Intent(getApplicationContext(),
                                org.thecongers.mcluster.UserSettingActivity.class);
                        startActivityForResult(i, SETTINGS_RESULT);
                        return true;
                    case R.id.action_about:
                        // About was selected
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.alert_about_title));
                        builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about));
                        builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null);
                        builder.show();
                        return true;
                    case R.id.action_exit:
                        // Exit menu item was selected
                        if (logger != null) {
                            logger.shutdown();
                        }
                        finish();
                        System.exit(0);
                    default:
                        return true;
                    }
                }
            });

            popup.show();
        }
    });

    layoutMiddleRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
            if (infoViewCurr < (numInfoViewLayouts - 1)) {
                infoViewCurr = infoViewCurr + 1;
            } else {
                infoViewCurr = 0;
            }
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString("prefInfoView", String.valueOf(infoViewCurr));
            editor.commit();

            //update layout
            updateLayout();
        }
    });

    canBusMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Check to see if message is the correct size
                if (msg.arg1 == 27) {
                    byte[] readBuf = (byte[]) msg.obj;
                    String message = new String(readBuf);

                    //Default Units
                    String speedUnit = "km/h";
                    String odometerUnit = "km";
                    String temperatureUnit = "C";

                    String[] splitMessage = message.split(",");
                    if (splitMessage[0].contains("10C")) {

                        //RPM
                        if (sharedPrefs.getString("prefInfoView", "0").contains("0")) {
                            int rpm = (Integer.parseInt(splitMessage[4], 16) * 255
                                    + Integer.parseInt(splitMessage[3], 16)) / 4;
                            txtInfo = (TextView) findViewById(R.id.textViewInfo);
                            txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM);
                            txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
                            txtInfo.setText(Integer.toString(rpm) + " RPM");
                            if (rpm > 8500) {
                                txtInfo.setTextColor(getResources().getColor(R.color.red));
                            } else {
                                txtInfo.setTextColor(getResources().getColor(android.R.color.black));
                            }
                        }

                        //Kill Switch
                        String killSwitchValue = splitMessage[5].substring(1);
                        if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) {
                            //Kill Switch On
                            imageKillSwitch.setImageResource(R.mipmap.kill_switch);
                        } else {
                            //Kill Switch Off
                            imageKillSwitch.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("130")) {
                        //Turn indicators
                        String indicatorValue = splitMessage[8];

                        if (indicatorValue.contains("D7")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        } else if (indicatorValue.contains("E7")) {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else if (indicatorValue.contains("EF")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        }

                        //High Beam
                        String highBeamValue = splitMessage[7].substring(1);
                        if (highBeamValue.contains("9")) {
                            //High Beam On
                            imageHighBeam.setImageResource(R.mipmap.high_beam);
                        } else {
                            //High Beam Off
                            imageHighBeam.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("294")) {
                        //Front Wheel Speed
                        double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                + Integer.parseInt(splitMessage[3], 16)) * 0.063);
                        //If 21" Wheel
                        if (sharedPrefs.getString("prefDistance", "0").contains("1")) {
                            frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                    + Integer.parseInt(splitMessage[3], 16)) * 0.064);
                        }
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            speedUnit = "MPH";
                            frontSpeed = frontSpeed / 1.609344;
                        }
                        txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed)));
                        txtSpeedUnit.setText(speedUnit);

                        //ABS
                        String absValue = splitMessage[2].substring(0, 1);
                        if (absValue.contains("B")) {
                            //ABS Off
                            imageABS.setImageResource(R.mipmap.abs);
                        } else {
                            //ABS On
                            imageABS.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("2BC")) {
                        //Engine Temperature
                        engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0;

                        if (engineTempC >= 115.5) {
                            if (engineTempAlertTriggered == false) {
                                engineTempAlertTriggered = true;
                                speakString(getResources().getString(R.string.engine_temp_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            engineTempAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double engineTemp = engineTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit);
                        }

                        // Gear
                        String gearValue = splitMessage[6].substring(0, 1);
                        String gear;
                        if (gearValue.contains("1")) {
                            gear = "1";
                        } else if (gearValue.contains("2")) {
                            gear = "N";
                        } else if (gearValue.contains("4")) {
                            gear = "2";
                        } else if (gearValue.contains("7")) {
                            gear = "3";
                        } else if (gearValue.contains("8")) {
                            gear = "4";
                        } else if (gearValue.contains("B")) {
                            gear = "5";
                        } else if (gearValue.contains("D")) {
                            gear = "6";
                        } else {
                            gear = "-";
                        }
                        txtGear.setText(gear);

                        //Air Temperature
                        airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0;
                        //Freeze Warning
                        if (airTempC <= 0.0) {
                            if (freezeAlertTriggered == false) {
                                freezeAlertTriggered = true;
                                speakString(getResources().getString(R.string.freeze_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            freezeAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double airTemp = airTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit);
                        }

                    } else if (splitMessage[0].contains("2D0")) {
                        //Info Button
                        String infoButtonValue = splitMessage[6].substring(1);
                        if (infoButtonValue.contains("5")) {
                            //Short Press
                            if (!btnPressed) {
                                int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
                                if (infoButton < (numInfoViewLayouts - 1)) {
                                    infoButton = infoButton + 1;
                                } else {
                                    infoButton = 0;
                                }
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(infoButton));
                                editor.commit();

                                //update layout
                                updateLayout();
                                btnPressed = true;
                            }
                        } else if (infoButtonValue.contains("6")) {
                            //Long Press
                        } else {
                            btnPressed = false;
                        }

                        //Heated Grips
                        String heatedGripSwitchValue = splitMessage[8].substring(0, 1);
                        if (heatedGripSwitchValue.contains("C")) {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        } else if (heatedGripSwitchValue.contains("D")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark);
                            }
                        } else if (heatedGripSwitchValue.contains("E")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
                            }
                        } else {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        }

                        //ESA Damping and Preload
                        String esaDampingValue1 = splitMessage[5].substring(1);
                        String esaDampingValue2 = splitMessage[8].substring(1);
                        String esaPreLoadValue = splitMessage[5].substring(0, 1);
                        if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaPreLoadValue.contains("1")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("3")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("4")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("6")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("7")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("8")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("9")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else {
                            txtESA.setText("");
                            imageESA.setImageResource(R.mipmap.blank_icon);
                        }

                        //Lamp Fault
                        //TODO: Display/speak Bulb location
                        String lampFaultValue = splitMessage[3].substring(0, 1);
                        if (lampFaultValue.contains("0")) {
                            //None
                            imageLampf.setImageResource(R.mipmap.blank_icon);
                        } else if (lampFaultValue.contains("1")) {
                            //Low Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("4")) {
                            //High Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("8")) {
                            //Signal Bulb
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else {
                            //Unknown
                            imageLampf.setImageResource(R.mipmap.lampf);
                        }

                        //Fuel Level
                        double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0)
                                * 100.0;
                        progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent));

                        //Fuel Level Warning
                        double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30);
                        if (fuelLevelPercent >= fuelWarning) {
                            imageFuelWarning.setImageResource(R.mipmap.blank_icon);
                            fuelAlertTriggered = false;
                            fuelReserveAlertTriggered = false;
                        } else if (fuelLevelPercent == 0) {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelReserveAlertTriggered) {
                                fuelReserveAlertTriggered = true;
                                //Audio Warning
                                speakString(getResources().getString(R.string.fuel_alert_reserve));
                            }
                        } else {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelAlertTriggered) {
                                fuelAlertTriggered = true;
                                //Audio Warning
                                String fuelAlert = getResources().getString(R.string.fuel_alert_begin)
                                        + String.valueOf((int) Math.round(fuelLevelPercent))
                                        + getResources().getString(R.string.fuel_alert_end);
                                speakString(fuelAlert);
                                //Suggest nearby fuel stations
                                if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) {
                                    // Display prompt to open google maps
                                    MainActivity.this.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                                    MainActivity.this);
                                            builder.setTitle(getResources()
                                                    .getString(R.string.alert_fuel_stations_title));
                                            if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) {
                                                // Search for fuel stations nearby
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_suggestions));
                                            } else if (sharedPrefs.getString("prefFuelStation", "0")
                                                    .contains("2")) {
                                                // Route to nearest fuel station
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_navigation));
                                            }
                                            builder.setPositiveButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_positive),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Uri gmmIntentUri = null;
                                                            if (sharedPrefs.getString("prefFuelStation", "0")
                                                                    .contains("1")) {
                                                                // Search for fuel stations nearby
                                                                gmmIntentUri = Uri
                                                                        .parse("geo:0,0?q=gas+station");
                                                            } else if (sharedPrefs
                                                                    .getString("prefFuelStation", "0")
                                                                    .contains("2")) {
                                                                // Route to nearest fuel station
                                                                gmmIntentUri = Uri.parse(
                                                                        "google.navigation:q=gas+station");
                                                            }
                                                            Intent mapIntent = new Intent(Intent.ACTION_VIEW,
                                                                    gmmIntentUri);
                                                            mapIntent
                                                                    .setPackage("com.google.android.apps.maps");
                                                            startActivity(mapIntent);
                                                        }
                                                    });
                                            builder.setNegativeButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_negative),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int id) {
                                                            dialog.cancel();
                                                        }
                                                    });
                                            builder.show();
                                        }
                                    });
                                }
                            }
                        }
                    } else if (splitMessage[0].contains("3F8")) {
                        String odometerValue = "";
                        for (int i = 4; i > 1; i--) {
                            odometerValue = odometerValue + splitMessage[i];
                        }
                        double odometer = Integer.parseInt(odometerValue, 16);
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            odometerUnit = "Miles";
                            odometer = odometer * 0.6214;
                        }
                        txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit);
                    }
                    imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on);
                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                        // Log data
                        if (logger == null) {
                            logger = new LogData();
                        }
                        if (logger != null) {
                            logger.write(message);
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "iTPMS Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        try {
                            // Get temperature
                            int tempC = Integer.parseInt(hexData[8], 16) - 50;
                            double temp = tempC;
                            String temperatureUnit = "C";
                            // Get tire pressure
                            int psi = Integer.parseInt(hexData[9], 16);
                            double pressure = psi;
                            String pressureUnit = "psi";
                            // Get battery voltage
                            double voltage = Integer.parseInt(hexData[10], 16) / 50;
                            // Get pressure thresholds
                            int lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30"));
                            int highPressure = Integer
                                    .parseInt(sharedPrefs.getString("prefHighPressure", "46"));
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                temp = (9.0 / 5.0) * tempC + 32.0;
                                temperatureUnit = "F";
                            }
                            int formattedTemperature = (int) (temp + 0.5d);
                            String pressureFormat = sharedPrefs.getString("prefPressureF", "0");
                            if (pressureFormat.contains("1")) {
                                // KPa
                                pressure = psi * 6.894757293168361;
                                pressureUnit = "KPa";
                            } else if (pressureFormat.contains("2")) {
                                // Kg-f
                                pressure = psi * 0.070306957965539;
                                pressureUnit = "Kg-f";
                            } else if (pressureFormat.contains("3")) {
                                // Bar
                                pressure = psi * 0.0689475729;
                                pressureUnit = "Bar";
                            }
                            int formattedPressure = (int) (pressure + 0.5d);
                            // Get checksum
                            String checksum = hexData[11];

                            if (Integer.parseInt(hexData[3], 16) <= 2) {
                                Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16));

                                frontPressurePSI = psi;
                                // Set front tire status
                                if (psi <= lowPressure) {
                                    frontStatus = 1;
                                } else if (psi >= highPressure) {
                                    frontStatus = 2;
                                } else {
                                    frontStatus = 0;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS);
                                    txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtFrontTPMS
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (frontStatus != 0) {
                                        txtFrontTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtFrontTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            } else if (Integer.parseInt(hexData[3], 16) > 2) {
                                Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16));

                                rearPressurePSI = psi;
                                // Set rear tire status
                                if (psi <= lowPressure) {
                                    rearStatus = 4;
                                } else if (psi >= highPressure) {
                                    rearStatus = 5;
                                } else {
                                    rearStatus = 3;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS);
                                    txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (rearStatus != 3) {
                                        txtRearTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtRearTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            }
                            // Reset icon
                            if ((frontStatus == 0) && (rearStatus == 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_on);
                            }
                            if ((frontStatus != 0) || (rearStatus != 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_alert);
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(2));
                                editor.commit();

                                updateLayout();

                                int delay = (Integer
                                        .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000);
                                String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                if (alertTimer == 0) {
                                    alertTimer = System.currentTimeMillis();
                                } else {
                                    long currentTime = System.currentTimeMillis();
                                    long duration = (currentTime - alertTimer);
                                    if (!currStatus.equals(lastStatus) || duration >= delay) {
                                        alertTimer = 0;
                                        if ((frontStatus == 1) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowFrontPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highFrontPressure));
                                        } else if ((rearStatus == 4) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowRearPressure));
                                        } else if ((rearStatus == 5) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontLowRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontHighRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontHighRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontLowRearPressure));
                                        }
                                        lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            Log.d(TAG, "Malformed message, unexpected value");
                        }
                        if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                            // Log data
                            if (logger == null) {
                                logger = new LogData();
                            }
                            if (logger != null) {
                                logger.write(String.valueOf(sbhex));
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    // Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    // Light
    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
    }
    // Compass
    sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
    sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);

    // Try to connect to CANBusGateway
    canBusConnect();
    // Connect to iTPMS if enabled
    if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        iTPMSConnect();
    }
}

From source file:com.yangtsaosoftware.pebblemessenger.activities.SetupFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 3) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(_context, this);

        } else {//from   w w w .j  a va  2s.c  om
            SpannableStringBuilder ssb = new SpannableStringBuilder();
            ssb.append(textInfo.getText());
            ssb.append(redText(R.string.setup_tts_failed));
            ssb.append('\n');
            textInfo.setText(ssb);
            svMyview.fullScroll(View.FOCUS_DOWN);
        }
    }
}

From source file:in.codehex.arrow.MainActivity.java

/**
 * Implement and manipulate the objects//from   w  ww . ja v  a  2s.  c  o m
 */
private void prepareObjects() {
    if (loginCheck()) {
        name = userPreferences.getString(Config.KEY_PREF_NAME, Config.PREF_DEFAULT_NAME);

        checkTts();

        textToSpeech = new TextToSpeech(this, this);
        textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {

            }

            @Override
            public void onDone(String utteranceId) {
                switch (utteranceId) {
                case Config.UTTERANCE_ID_INITIAL:
                    promptSpeechInput();
                    break;
                case Config.UTTERANCE_ID_CONFIRMATION:
                    promptSpeechInput();
                    break;
                }
            }

            @Override
            public void onError(String utteranceId) {

            }
        });

        mainLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textToSpeech.speak(getString(R.string.prompt_speech_input_initial), TextToSpeech.QUEUE_FLUSH,
                        null, Config.UTTERANCE_ID_INITIAL);
            }
        });

        if (checkPlayServices())
            buildGoogleApiClient();

        createLocationRequest();

        if (!isGPSEnabled(getApplicationContext()))
            showAlertGPS();
    }
}

From source file:com.rnd.snapsplit.view.OcrCaptureFragment.java

/**
 * Initializes the UI and creates the detector pipeline.
 *///w ww  .j  a  v a 2 s  . co  m
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
//            Toast.makeText(getContext(), "pic saved", Toast.LENGTH_LONG).show();
//            Log.d("CameraDemo", "Pic saved");
//        }
//    }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.view_ocr_capture, container, false);
    final Activity activity = getActivity();
    final Context context = getContext();

    ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger))
            .setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));
    final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + "/picFolder/";
    File newdir = new File(dir);
    newdir.mkdirs();

    mPreview = (CameraSourcePreview) view.findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) view.findViewById(R.id.graphicOverlay);

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

    // Set good defaults for capturing text.
    boolean autoFocus = true;
    boolean useFlash = false;

    //        createNewThread();
    //        t.start();

    final ImageView upArrow = (ImageView) view.findViewById(R.id.arrow_up);
    upArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (rotationAngle == 0) { // arrow up
                //mCameraSource.takePicture(null, mPicture);
                //mGraphicOverlay.clear();
                //                    mGraphicOverlay.clear();
                //                    mGraphicOverlay.amountItem = null;
                onPause();
                //shouldContinue = false;
                //mCamera.takePicture(null, null, mPicture);

                File pictureFile = getOutputMediaFile();
                if (pictureFile == null) {
                    return;
                }
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
                    receiptBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    picPath = pictureFile.getAbsolutePath();
                    //fos.write(mCameraSource.mostRecentBitmap);
                    fos.close();
                } catch (FileNotFoundException e) {

                } catch (IOException e) {
                }

                upArrow.animate().rotation(180).setDuration(500).start();

                TextView amount = (TextView) view.findViewById(R.id.text_amount_value);
                if (mGraphicOverlay.amountItem == null) {
                    amount.setText("0.00");
                } else {
                    amount.setText(String.format("%.2f", mGraphicOverlay.amountItemAfterFormat));
                }
                TextView desc = (TextView) view.findViewById(R.id.text_name_value);
                desc.setText(mGraphicOverlay.description);

                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                box.setVisibility(View.VISIBLE);
                Animation slide_up = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_up);

                box.startAnimation(slide_up);
                rotationAngle = 180;

            } else {
                //                    t.interrupt();
                //                    t = null;
                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                Animation slide_down = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_down);

                upArrow.animate().rotation(0).setDuration(500).start();

                box.startAnimation(slide_down);
                box.setVisibility(View.INVISIBLE);
                //shouldContinue = true;
                mGraphicOverlay.amountItem = null;
                mGraphicOverlay.amountItemAfterFormat = 0f;
                mGraphicOverlay.description = "";
                onResume();
                //                    createNewThread();
                //                    t.start();
                rotationAngle = 0;
            }
        }
    });

    ImageView addButton = (ImageView) view.findViewById(R.id.add_icon);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // takePicture();
            EditText description = (EditText) view.findViewById(R.id.text_name_value);
            EditText amount = (EditText) view.findViewById(R.id.text_amount_value);
            float floatAmount = Float.parseFloat(amount.getText().toString());
            Summary t = new Summary(description.getText().toString(), floatAmount);

            Bundle bundle = new Bundle();
            bundle.putSerializable("splitTransaction", t);

            //                 ByteArrayOutputStream stream = new ByteArrayOutputStream();
            //                 mCameraSource.mostRecentBitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
            //                 byte[] byteArray = stream.toByteArray();
            //Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
            //bundle.putParcelable("receiptPicture",receiptBitmap);
            bundle.putString("receiptPicture", picPath);

            FriendsSelectionFragment fragment = new FriendsSelectionFragment();
            fragment.setArguments(bundle);

            ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger)).setVisibility(View.INVISIBLE);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_holder, fragment, "FriendsSelectionFragment").addToBackStack(null)
                    .commit();
        }
    });

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {
        requestCameraPermission();
    }

    gestureDetector = new GestureDetector(context, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());

    //        Snackbar.make(mGraphicOverlay, "Tap to Speak. Pinch/Stretch to zoom",
    //                Snackbar.LENGTH_LONG)
    //                .show();

    // Set up the Text To Speech engine.
    TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(final int status) {
            if (status == TextToSpeech.SUCCESS) {
                Log.d("OnInitListener", "Text to speech engine started successfully.");
                tts.setLanguage(Locale.US);
            } else {
                Log.d("OnInitListener", "Error starting the text to speech engine.");
            }
        }
    };
    tts = new TextToSpeech(activity.getApplicationContext(), listener);

    return view;
}

From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setHasOptionsMenu(true);/*w w w .ja v  a2 s  .  c o m*/
    this.bookView.init();

    this.progressBar.setFocusable(true);
    this.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        private int seekValue;

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            bookView.navigateToPercentage(this.seekValue);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                seekValue = progress;
                percentageField.setText(progress + "% ");
            }
        }
    });

    this.mediaProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                seekToPointInPlayback(progress);
            }
        }
    });

    this.textToSpeech = new TextToSpeech(context, this::onTextToSpeechInit);

    this.bookView.addListener(this);
    this.bookView.setTextSelectionCallback(this);
}

From source file:com.hughes.android.dictionary.DictionaryActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    // This needs to be before super.onCreate, otherwise ActionbarSherlock
    // doesn't makes the background of the actionbar white when you're
    // in the dark theme.
    setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);

    Log.d(LOG, "onCreate:" + this);
    super.onCreate(savedInstanceState);

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Don't auto-launch if this fails.
    prefs.edit().remove(C.DICT_FILE).commit();

    setContentView(R.layout.dictionary_activity);

    application = (DictionaryApplication) getApplication();
    theme = application.getSelectedTheme();
    textColorFg = getResources().getColor(theme.tokenRowFgColor);

    final Intent intent = getIntent();
    String intentAction = intent.getAction();
    /**/*from   ww w  .  j  a v  a2  s  .co m*/
     * @author Dominik Kppl Querying the Intent
     *         com.hughes.action.ACTION_SEARCH_DICT is the advanced query
     *         Arguments: SearchManager.QUERY -> the phrase to search from
     *         -> language in which the phrase is written to -> to which
     *         language shall be translated
     */
    if (intentAction != null && intentAction.equals("com.hughes.action.ACTION_SEARCH_DICT")) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        String from = intent.getStringExtra("from");
        if (from != null)
            from = from.toLowerCase(Locale.US);
        String to = intent.getStringExtra("to");
        if (to != null)
            to = to.toLowerCase(Locale.US);
        if (query != null) {
            getIntent().putExtra(C.SEARCH_TOKEN, query);
        }
        if (intent.getStringExtra(C.DICT_FILE) == null && (from != null || to != null)) {
            Log.d(LOG, "DictSearch: from: " + from + " to " + to);
            List<DictionaryInfo> dicts = application.getDictionariesOnDevice(null);
            for (DictionaryInfo info : dicts) {
                boolean hasFrom = from == null;
                boolean hasTo = to == null;
                for (IndexInfo index : info.indexInfos) {
                    if (!hasFrom && index.shortName.toLowerCase(Locale.US).equals(from))
                        hasFrom = true;
                    if (!hasTo && index.shortName.toLowerCase(Locale.US).equals(to))
                        hasTo = true;
                }
                if (hasFrom && hasTo) {
                    if (from != null) {
                        int which_index = 0;
                        for (; which_index < info.indexInfos.size(); ++which_index) {
                            if (info.indexInfos.get(which_index).shortName.toLowerCase(Locale.US).equals(from))
                                break;
                        }
                        intent.putExtra(C.INDEX_SHORT_NAME, info.indexInfos.get(which_index).shortName);

                    }
                    intent.putExtra(C.DICT_FILE, application.getPath(info.uncompressedFilename).toString());
                    break;
                }
            }

        }
    }
    /**
     * @author Dominik Kppl Querying the Intent Intent.ACTION_SEARCH is a
     *         simple query Arguments follow from android standard (see
     *         documentation)
     */
    if (intentAction != null && intentAction.equals(Intent.ACTION_SEARCH)) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (query != null)
            getIntent().putExtra(C.SEARCH_TOKEN, query);
    }
    /**
     * @author Dominik Kppl If no dictionary is chosen, use the default
     *         dictionary specified in the preferences If this step does
     *         fail (no default directory specified), show a toast and
     *         abort.
     */
    if (intent.getStringExtra(C.DICT_FILE) == null) {
        String dictfile = prefs.getString(getString(R.string.defaultDicKey), null);
        if (dictfile != null)
            intent.putExtra(C.DICT_FILE, application.getPath(dictfile).toString());
    }
    String dictFilename = intent.getStringExtra(C.DICT_FILE);

    if (dictFilename == null) {
        Toast.makeText(this, getString(R.string.no_dict_file), Toast.LENGTH_LONG).show();
        startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
        finish();
        return;
    }
    if (dictFilename != null)
        dictFile = new File(dictFilename);

    ttsReady = false;
    textToSpeech = new TextToSpeech(getApplicationContext(), new OnInitListener() {
        @Override
        public void onInit(int status) {
            ttsReady = true;
            updateTTSLanguage(indexIndex);
        }
    });

    try {
        final String name = application.getDictionaryName(dictFile.getName());
        this.setTitle("QuickDic: " + name);
        dictRaf = new RandomAccessFile(dictFile, "r");
        dictionary = new Dictionary(dictRaf);
    } catch (Exception e) {
        Log.e(LOG, "Unable to load dictionary.", e);
        if (dictRaf != null) {
            try {
                dictRaf.close();
            } catch (IOException e1) {
                Log.e(LOG, "Unable to close dictRaf.", e1);
            }
            dictRaf = null;
        }
        Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG)
                .show();
        startActivity(DictionaryManagerActivity.getLaunchIntent(getApplicationContext()));
        finish();
        return;
    }
    String targetIndex = intent.getStringExtra(C.INDEX_SHORT_NAME);
    if (savedInstanceState != null && savedInstanceState.getString(C.INDEX_SHORT_NAME) != null) {
        targetIndex = savedInstanceState.getString(C.INDEX_SHORT_NAME);
    }
    indexIndex = 0;
    for (int i = 0; i < dictionary.indices.size(); ++i) {
        if (dictionary.indices.get(i).shortName.equals(targetIndex)) {
            indexIndex = i;
            break;
        }
    }
    Log.d(LOG, "Loading index " + indexIndex);
    index = dictionary.indices.get(indexIndex);
    setListAdapter(new IndexAdapter(index));

    // Pre-load the collators.
    new Thread(new Runnable() {
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            final long startMillis = System.currentTimeMillis();
            try {
                TransliteratorManager.init(new TransliteratorManager.Callback() {
                    @Override
                    public void onTransliteratorReady() {
                        uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                onSearchTextChange(searchView.getQuery().toString());
                            }
                        });
                    }
                });

                for (final Index index : dictionary.indices) {
                    final String searchToken = index.sortedIndexEntries.get(0).token;
                    final IndexEntry entry = index.findExact(searchToken);
                    if (entry == null || !searchToken.equals(entry.token)) {
                        Log.e(LOG, "Couldn't find token: " + searchToken + ", "
                                + (entry == null ? "null" : entry.token));
                    }
                }
                indexPrepFinished = true;
            } catch (Exception e) {
                Log.w(LOG,
                        "Exception while prepping.  This can happen if dictionary is closed while search is happening.");
            }
            Log.d(LOG, "Prepping indices took:" + (System.currentTimeMillis() - startMillis));
        }
    }).start();

    String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.otf.jpg");
    if ("SYSTEM".equals(fontName)) {
        typeface = Typeface.DEFAULT;
    } else if ("SERIF".equals(fontName)) {
        typeface = Typeface.SERIF;
    } else if ("SANS_SERIF".equals(fontName)) {
        typeface = Typeface.SANS_SERIF;
    } else if ("MONOSPACE".equals(fontName)) {
        typeface = Typeface.MONOSPACE;
    } else {
        if ("FreeSerif.ttf.jpg".equals(fontName)) {
            fontName = "FreeSerif.otf.jpg";
        }
        try {
            typeface = Typeface.createFromAsset(getAssets(), fontName);
        } catch (Exception e) {
            Log.w(LOG, "Exception trying to use typeface, using default.", e);
            Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()), Toast.LENGTH_LONG)
                    .show();
        }
    }
    if (typeface == null) {
        Log.w(LOG, "Unable to create typeface, using default.");
        typeface = Typeface.DEFAULT;
    }
    final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
    try {
        fontSizeSp = Integer.parseInt(fontSize.trim());
    } catch (NumberFormatException e) {
        fontSizeSp = 14;
    }

    // ContextMenu.
    registerForContextMenu(getListView());

    // Cache some prefs.
    wordList = application.getWordListFile();
    saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
    clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
    Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);

    onCreateSetupActionBarAndSearchView();

    // Set the search text from the intent, then the saved state.
    String text = getIntent().getStringExtra(C.SEARCH_TOKEN);
    if (savedInstanceState != null) {
        text = savedInstanceState.getString(C.SEARCH_TOKEN);
    }
    if (text == null) {
        text = "";
    }
    setSearchText(text, true);
    Log.d(LOG, "Trying to restore searchText=" + text);

    setDictionaryPrefs(this, dictFile, index.shortName, searchView.getQuery().toString());

    updateLangButton();
    searchView.requestFocus();

    // http://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling
    //        getListView().setCacheColorHint(0);
}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setHasOptionsMenu(true);/*from ww w .ja  v a 2 s.c om*/
    this.bookView.init();

    this.progressBar.setFocusable(true);
    this.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        private int seekValue;

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            bookView.navigateToPercentage(this.seekValue);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                seekValue = progress;
                percentageField.setText(progress + "% ");
            }
        }
    });

    this.mediaProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                seekToPointInPlayback(progress);
            }
        }
    });

    this.textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            onTextToSpeechInit(status);
        }
    });

    this.bookView.addListener(this);
    this.bookView.setTextSelectionCallback(this);
}

From source file:atlc.granadaaccessibilityranking.VoiceActivity.java

/**
 * Starts the TTS engine. It is work-around to avoid implementing the UtteranceProgressListener abstract class.
 *
 * @author Method by Greg Milette (comments incorporated by us). Source: https://github.com/gast-lib/gast-lib/blob/master/library/src/root/gast/speech/voiceaction/VoiceActionExecutor.java
 * @see See the problem here: http://stackoverflow.com/questions/11703653/why-is-utteranceprogresslistener-not-an-interface
 *//*from ww w  .  j av a  2  s  . co  m*/
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void setTTS() {
    myTTS = new TextToSpeech(ctx, (OnInitListener) this);

    /*
     * The listener for the TTS events varies depending on the Android version used:
     * the most updated one is UtteranceProgressListener, but in SKD versions
     * 15 or earlier, it is necessary to use the deprecated OnUtteranceCompletedListener
     */

    if (Build.VERSION.SDK_INT >= 15) {
        myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onDone(String utteranceId) //TTS finished synthesizing
            {
                onTTSDone(utteranceId);
            }

            @Override
            public void onError(String utteranceId) //TTS encountered an error while synthesizing
            {
                onTTSError(utteranceId);
            }

            @Override
            public void onStart(String utteranceId) //TTS has started synthesizing
            {
                onTTSStart(utteranceId);
            }
        });
    } else {
        myTTS.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
            @Override
            public void onUtteranceCompleted(final String utteranceId) {
                onTTSDone(utteranceId); //Earlier SDKs only consider the onTTSDone event
            }
        });
    }
}

From source file:onion.chat.MainActivity.java

private void inform() {
    t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override/*from   w ww.  j a v  a2  s  .c  om*/
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                t1.setLanguage(Locale.US);
            }
        }
    });
    String toSpeak = "Welcome to Its Ur's an Instant Messaging app!";
    Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
    t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}

From source file:com.morlunk.mumbleclient.service.PlumbleService.java

/**
 * Called when the user makes a change to their preferences. Should update all preferences relevant to the service.
 *//*from  w ww  .j a  v  a 2 s.  c  o m*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (!isConnected())
        return; // These properties should all be set on connect regardless.

    if (Settings.PREF_INPUT_METHOD.equals(key)) {
        /* Convert input method defined in settings to an integer format used by Jumble. */
        int inputMethod = mSettings.getJumbleInputMethod();
        try {
            getBinder().setTransmitMode(inputMethod);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mChannelOverlay.setPushToTalkShown(inputMethod == Constants.TRANSMIT_PUSH_TO_TALK);
    } else if (Settings.PREF_HANDSET_MODE.equals(key)) {
        setProximitySensorOn(mSettings.isHandsetMode());
    } else if (Settings.PREF_THRESHOLD.equals(key)) {
        try {
            getBinder().setVADThreshold(mSettings.getDetectionThreshold());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else if (Settings.PREF_HOT_CORNER_KEY.equals(key)) {
        mHotCorner.setGravity(mSettings.getHotCornerGravity());
        mHotCorner.setShown(mSettings.isHotCornerEnabled());
    } else if (Settings.PREF_USE_TTS.equals(key)) {
        if (mTTS == null && mSettings.isTextToSpeechEnabled())
            mTTS = new TextToSpeech(this, mTTSInitListener);
        else if (mTTS != null && !mSettings.isTextToSpeechEnabled()) {
            mTTS.shutdown();
            mTTS = null;
        }
    } else if (Settings.PREF_AMPLITUDE_BOOST.equals(key)) {
        try {
            getBinder().setAmplitudeBoost(mSettings.getAmplitudeBoostMultiplier());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else if (Settings.PREF_HALF_DUPLEX.equals(key)) {
        try {
            getBinder().setHalfDuplex(mSettings.isHalfDuplex());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else if (Settings.PREF_PTT_SOUND.equals(key)) {
        mPTTSoundEnabled = mSettings.isPttSoundEnabled();
    }
}