Search code examples
androidkeylistenervibration

Using the OnKeyListener to make the phone vibrate


I am trying to make my phone vibrate whenever I type in a specific word into the onKeyListener.

I came up with this code which I thought would work but sadly, it doesn't. The done button doesn't appear in portrait and the phone (galaxy s3) remains motionless when I type in the correct phrase.

I always get this in the logcat "SendUserActionEvent()==null;". Thank you for your time.

public class MainActivity extends Activity {

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    final TextView text = (TextView)findViewById(R.id.text);
    EditText edittext = (EditText)findViewById(R.id.editText);
    edittext.setImeOptions(EditorInfo.IME_ACTION_DONE);
    edittext.setOnKeyListener(new OnKeyListener(){

        @Override
        public boolean onKey(View view, int keycode, KeyEvent evt) {
            if (evt.getAction()== KeyEvent.ACTION_DOWN)
            {
                if(keycode == KeyEvent.KEYCODE_ENTER){

                    if (this.equals("Vibrate")){
                        Vibrator vibrate = (Vibrator)    
                        getSystemService(Context.VIBRATOR_SERVICE);
                        vibrate.vibrate(1000);

                    }
                    else{
                        text.setText("Didn't Vibrate");
                    }

                }   
                }

            // TODO Auto-generated method stub
            return true; 
        }
    });
}


}

Solution

  • You probably want to use the TextWatcher http://developer.android.com/reference/android/text/TextWatcher.html

    edittext.addTextChangedListener(new TextWatcher() {
       @Override
       public void afterTextChanged(Editable e) {
            if ("Vibrate".equals(e.toString()) {
                // Vibrate the phone
            }
    
       }
       //... other methods
    }
    

    Also, don't forget to add the VIBRATE permission to your manifest. Worst comes to worse, step through your code to try to understand what is happening.