Example usage for android.media ToneGenerator startTone

List of usage examples for android.media ToneGenerator startTone

Introduction

In this page you can find the example usage for android.media ToneGenerator startTone.

Prototype

public boolean startTone(int toneType) 

Source Link

Document

This method starts the playback of a tone of the specified type.

Usage

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle the receipt of suggestions from the spell checker
 * colour the text in the editor as required
 * pass information to the keyboard view so it can draw the colour bar
 * initiate audio and haptic feedback as required
 *//*from w  w w .ja  va  2s  . co m*/
@Override
public void onGetSuggestions(SuggestionsInfo[] results) {
    // TODO Auto-generated method stub
    int colortype = -1;
    final StringBuilder sb = new StringBuilder();

    if (updateSuggestionList) {
        updateSuggestionList = false;
        ArrayList<String> s = new ArrayList<String>();
        for (int i = 0; i < results.length; ++i) {
            final int length = results[i].getSuggestionsCount();
            for (int j = 0; j < length; ++j) {
                s.add(results[i].getSuggestionAt(j));
            }
        }
        updateSuggestionListWithSpellChecker(s);
    } else {

        for (int i = 0; i < results.length; ++i) {
            // Returned suggestions are contained in SuggestionsInfo

            final int len = results[i].getSuggestionsCount();
            sb.append("Suggestion Attribs: " + results[i].getSuggestionsAttributes());
            if ((results[i].getSuggestionsAttributes()
                    & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) == SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) {
                sb.append("The word was found in the dictionary\n");
                mInputView.wordcompletedtype = 3;
            } else {

                if ((results[i].getSuggestionsAttributes()
                        & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) == SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) {
                    if ((results[i].getSuggestionsAttributes()
                            & SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) == SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) {
                        colortype = 1; //yellow
                        mInputView.wordcompletedtype = 1;
                        sb.append("There are strong candidates for this word\n");
                        currentSession.nLowErrors++;
                    } else {
                        colortype = 2; //red
                        mInputView.wordcompletedtype = 2;
                        sb.append("The word looks like a typo\n");
                        currentSession.nHighErrors++;

                    }
                }

            }

            sb.append("\n--These are the suggestions--\n");
            for (int j = 0; j < len; ++j) {
                sb.append("," + results[i].getSuggestionAt(j));
            }
            sb.append(" (" + len + ")");
        }
        //Log.i("Spelling suggestions", sb.toString());

        //this comes after a word separator, hence just add 1 to the cursor
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        SpannableString text = new SpannableString(mComposingTemp);

        if (sharedPrefs.getBoolean("highlightwords", true)) {
            switch (colortype) {
            case 1:
                text.setSpan(new BackgroundColorSpan(small_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2:
                text.setSpan(new BackgroundColorSpan(big_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                break;
            }
        }

        if (sharedPrefs.getBoolean("autocorrect", true) && mInputView.wordcompletedtype == 1) //handle autocorrection
        {
            SpannableString autoc = autocorrect(results);
            autocorrected_words.put(autoc.toString(), text.toString()); //autocorrected word, original input
            //Log.i("Autocorrecting","Key= "+autoc.toString()+", Value= "+text.toString());
            text = autoc;
            if (sharedPrefs.getBoolean("highlightwords", true))
                text.setSpan(new BackgroundColorSpan(autocorrect), 0, text.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mInputView.wordcompletedtype = 4;
        } else //autocorrection is turned off
        {
            if (!sharedPrefs.getBoolean("autocorrect", true) && colortype >= 1) //a mistake word
            {
                //Log.i("OnGetSentenceSuggestions","Key= "+text.toString()+", Value= "+text.toString());
                //no autocorrects, just put the word in and itself as the replacement
                autocorrected_words.put(text.toString(), text.toString());
            }
        }

        if (sharedPrefs.getBoolean("vibrator", false)) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            final int on_time = Integer.parseInt(sharedPrefs.getString("shortvibe", "35"));

            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                // Vibrate for 300 milliseconds
                v.vibrate(on_time);
                break;
            case 2: //big err
                //v.vibrate(Integer.parseInt(sharedPrefs.getString("longvibe", "300")));
                v.vibrate(new long[] { 0, on_time, 200, on_time }, -1);
                break;
            case 4: //autocorr
                v.vibrate(on_time);
                break;
            default:
                break;

            }
        }

        if (sharedPrefs.getBoolean("audio", false)) {
            final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            case 2: //big err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                break;
            case 4: //autocorr
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            default:
                break;

            }
        }

        mInputView.invalidateAllKeys();
        ic.commitText(text, 1);
        sendKey(wordSeparatorKeyCode);
        coreEngine.resetCoreString();
        updateCandidates();
    }

}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Manages actual input into the editor. Here we:
 * implement our injection algorithm as required
 * store data relating to the key press/* ww w. j ava  2s  .com*/
 * initiate any spell checking as required
 */
public void onKey(int primaryCode, int[] keyCodes) {

    // touches all done, add the chars to the event and then the event to the session       
    currentEvent.keyCode = primaryCode;

    if (errorInjection && primaryCode >= 32) {
        //give a n% chance of the key being modified
        Random r = new Random();
        int res = r.nextInt(100);
        if (res <= errorInjectionThreshold) //%n chance of key being modified
        {
            //Log.i("OnKey", "Will modify");
            try {
                //for each combination in the model, find the eucleidian distance and the replacement freq
                JSONObject targetObj = suspectReplacementDistribution
                        .getJSONObject(Integer.toString(primaryCode));
                Iterator<?> keys = targetObj.keys();
                ArrayList<Character> list = new ArrayList();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    int freq = targetObj.getInt(key);
                    //if the frequency is 0, add the suspect as a replacement candidate
                    double dist = keyModel.distance2(primaryCode, Integer.parseInt(key));

                    if (dist > 0) {
                        if (dist > 2.0) //fix it so that only nearby keys have a chance of being elected
                            dist = 100;
                        //add to the list of candidates as many times as required if specific freq>0;
                        int sfreq = (int) Math.round(freq / dist);
                        //Log.i("Test", "Freq/Dist to "+key+": "+freq+"/"+dist+" final prob: "+sfreq);

                        if (sfreq == 0) //add the suspect as a replacement candidate
                        {
                            list.add(Character.toChars(primaryCode)[0]);
                        } else //add the other replacement candidates as required
                        {
                            for (int x = 0; x < targetObj.getInt(key); x++) {
                                list.add(Character.toChars(Integer.parseInt(key))[0]);

                            }
                        }
                    }
                }
                //Log.i("OnKey", "Replace list size: "+list.size());

                Random x = new Random();
                int sel = x.nextInt(list.size());

                //if the replacement eventually happens
                if ((int) list.get(sel) != primaryCode) {

                    if (errorInjectionSound) {
                        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
                        tg.startTone(ToneGenerator.TONE_CDMA_SOFT_ERROR_LITE);
                    }
                    //primaryCode = (int)list.get(sel);

                    //Log.w("OnKey", "Replace "+Character.toChars(primaryCode)[0]+" with "+list.get(sel));
                    errorMap.put(mComposing.length(), (char) (int) list.get(sel)); //put in our current position and the replacement
                    //nInjections++;      
                } else
                    Log.i("OnKey", "Replacement will not happen, same key selected");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            //Log.i("OnKey", "Will not modify, r="+res);
        }
    }
    //switch adaptxt language if necessary
    if (coreEngine != null) {
        switch (mInputView.currentKeyboard) {
        case KeyboardViews.QWERTY_EL:
            coreEngine.activateLanguageKeymap(131092, null);
            coreEngine.setDictionaryPriority(131092, 0);
            break;
        case KeyboardViews.QWERTY_EN:
            coreEngine.activateLanguageKeymap(131081, null);
            coreEngine.setDictionaryPriority(131092, 1);
            break;
        }
    }

    //get the full inputted text
    extr = ic.getExtractedText(new ExtractedTextRequest(), 0);

    if (currentEvent != null && captureData == true) {

        //Log.i("OnKey", "OK to capture data!");
        currentEvent.user = userid;

        if (primaryCode > 0)
            currentEvent.keyChar = (char) primaryCode;

        //handle the booleans
        if (currentSession.events.get(currentSession.events.size() - 1).keyChar == ' ') //space
        {
            currentEvent.followsSpace = true;
        }

        if (currentEvent.keyCode == Keyboard.KEYCODE_DELETE) {
            System.out.println("Backspace Pressed!");

            //if a delete is pressed after another delete
            //and its cursor position is not -1 from the previous delete
            //we must commit the previous deletion as a suspect character.
            if (currentSession.events.get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE
                    && extr.selectionStart != lastDeletedPos - 1) {
                currentSession.suspects.add(lastDeleted);
                //System.out.println("Suspect = "+lastDeleted);
            }

            //get all the text before the backspace press and the current cursor position
            if (extr.selectionStart > 0) {
                lastDeleted = extr.text.charAt(extr.selectionStart - 1);
                lastDeletedPos = extr.selectionStart;
                //System.out.println("Deleted = "+lastDeleted+"\nCursor Position = "+extr.selectionStart);
            }
        }

        //if the current key is NOT a backspace but the previous one was
        if (currentEvent.keyCode != Keyboard.KEYCODE_DELETE && currentSession.events
                .get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE) {
            currentSession.suspects.add(lastDeleted);
            //System.out.println("Suspect = "+lastDeleted);

        }

    }

    //do the handling     
    if (isWordSeparator(primaryCode)) {
        // Handle separator
        //System.out.println("Detected a word separator \""+primaryCode+"\"");
        if (primaryCode != 32) {
            shouldInsertSpace = false;
            if (extr.text.length() > 0) {
                //Log.i("On Key ", "last letter after separator was ["+extr.text.charAt(extr.selectionStart-1)+"]");
                //check if the previous char was a space, if so delete it.
                if (extr.text.charAt(extr.selectionStart - 1) == ' ' && !isSpecialSeparator(primaryCode)) //detecting if the current char is not part of a smiley face
                {
                    onKey(-5, null);
                }
            }
        }

        //clear the touch history
        clearDots();

        //ensure spell checker is using correct language          
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        Editor ed = prefs.edit();
        if (captureData) {
            if (mInputView.currentLang == 1) //english
            {
                ed.putString("available_dicts", "en");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale english = new Locale("en", "GB");
                mScs = tsm.newSpellCheckerSession(null, english, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            } else {
                ed.putString("available_dicts", "el");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale greek = new Locale("el", "GR");
                mScs = tsm.newSpellCheckerSession(null, greek, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            }
        }

        //handle space for Adaptxt
        if (Character.isSpaceChar(primaryCode)) {
            if (coreEngine != null) {
                //Log.i("Handle Character", "Space pressed");
                coreEngine.resetCoreString();
                //Log.i("Space Pressed", "Word is "+mComposing+" ");
                coreEngine.insertText(mComposing.toString() + " ");
                updateCandidates();
            }
        }

        if (!firstWordSet && mComposing.length() > 1) {
            if (captureData)
                currentSession.firstWord = mComposing.toString();
            else
                currentSession.firstWord = "$$$$";

            firstWordSet = true;
            //System.out.println("First Word\""+mComposing.toString()+"\"");
        }

        //effect any injections as required
        if (mComposing.length() > 0) {
            //commitTyped(getCurrentInputConnection());
            //check the errormap for any replacements 
            if (errorMap.size() > 0) {

                //restrict the errormap to the 25% of word length cap

                int replacementstodelete = errorMap.size() - (int) Math.round(mComposing.length() * 0.25); //total replacements - those to keep
                if (replacementstodelete < 0)
                    replacementstodelete = 0;
                //allow at least one
                if (errorMap.size() == replacementstodelete)
                    replacementstodelete = errorMap.size() - 1;

                if (replacementstodelete > 0) {
                    List<Integer> keys = new ArrayList<Integer>(errorMap.keySet());

                    for (int z = 0; z < replacementstodelete; z++) {
                        Random random = new Random();
                        int listposition = random.nextInt(keys.size());
                        int randomKey = keys.get(listposition);
                        //remove this from the error map and the list
                        errorMap.remove(randomKey);
                        keys.remove(listposition);

                    }
                }

                //effect the injections
                String oldmComposing = mComposing.toString();
                Iterator it = errorMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    mComposing.replace((Integer) pair.getKey(), (Integer) pair.getKey() + 1,
                            "" + (Character) pair.getValue());
                    //it.remove(); // avoids a ConcurrentModificationException
                }
                nInjections += errorMap.size();
                currentSession.nInjections = nInjections;
                //Log.i("Injections", "Will replace "+oldmComposing+" with "+mComposing+", nInjections="+nInjections);
                errorMap.clear();
            }

            wordSeparatorKeyCode = primaryCode;
            if (captureData)
                commitTyped(ic, isWordSeparator(primaryCode));
            else {
                if (primaryCode != Keyboard.KEYCODE_DONE && primaryCode != 10) //done and go/enter
                    handleCharacter(primaryCode, keyCodes);
                else
                    sendKey(primaryCode);
                commitTyped(ic);
            }
        } else {
            sendKey(primaryCode);
        }

        updateShiftKeyState(getCurrentInputEditorInfo());

    } else if (primaryCode == Keyboard.KEYCODE_DELETE) {
        if (errorMap.get(mComposing.length() - 1) != null) {
            //Log.i("Injection", "Delete from map pos="+(mComposing.length()-1)+", char="+errorMap.get(mComposing.length()-1));
            errorMap.remove(mComposing.length() - 1);
        }

        handleBackspace();
    } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
        handleShift();
    } else if (primaryCode == Keyboard.KEYCODE_CANCEL) { //keyboard hiding button
        //override this for settings activity
        //handleClose();
        Intent intent = new Intent(this, LoggingIMESettings.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return;
    } else if (primaryCode == LatinKeyboardView.KEYCODE_OPTIONS) {
        // Show a menu or somethin'
    } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE && mInputView != null) {
        //Keyboard current = mInputView.getKeyboard();

        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS
                || mInputView.currentKeyboard == KeyboardViews.SYMBOLS_SHIFTED) {
            //mInputView.currentKeyboard = KeyboardViews.QWERTY_EN;
            mInputView.currentKeyboard = lastKeyboardView;
        } else { //about to change to symbols
            lastKeyboardView = mInputView.currentKeyboard; //keep track of where we came from
            mInputView.currentKeyboard = KeyboardViews.SYMBOLS;
        }
        mInputView.switchKeyboard();
        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS) {
            mInputView.getKeyboard().setShifted(false);
        }
    } else {
        handleCharacter(primaryCode, keyCodes);
    }
}