Android Vibrate on touch?

Fof*_*ole 13 android android-vibration

当我触摸屏幕上的对象时,我试图让我的设备振动.我正在使用此代码:

 Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE); 
 v.vibrate(300);    
Run Code Online (Sandbox Code Playgroud)

使用清单文件中的权限但我似乎没有得到任何结果.有什么建议?此外,我的硬件支持振动.

Ram*_*nki 22

请试试这个:

Button b = (Button) findViewById(R.id.button1);
    b.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            Vibrator vb = (Vibrator)   getSystemService(Context.VIBRATOR_SERVICE);
            vb.vibrate(100);
            return false;
        }
    });
Run Code Online (Sandbox Code Playgroud)

并将此权限添加到manifest.xml

 <uses-permission android:name="android.permission.VIBRATE"/>
Run Code Online (Sandbox Code Playgroud)


Den*_*aia 22

根据这个答案,您可以执行触觉反馈(振动)而无需任何额外的权限.看performHapticFeedback方法.

View view = findViewById(...)
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Run Code Online (Sandbox Code Playgroud)

注意:我没有测试过这段代码.