In the development, we often meet the scene that needs vibration. Here we provide the code to call the vibration function of Android system for your reference. First we need to get the class that operates the vibration function
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Copy the code
Second, we need to activate the vibration function. Here we need to specify how long a vibration takes in milliseconds.
vibrator.vibrate(3000); // Vibrate for 3 secondsCopy the code
If we’re in the middle of shaking and we don’t want to shake, like when the user clicks OK, we need to pause the shaking
vibrator.cancel();
Copy the code
Of course, we also need to determine whether the current device has vibration capability before implementing these features.
vibrator.hasVibrator();
Copy the code
The vibration function uses the following permissions
<uses-permission android:name="android.permission.VIBRATE"/>
Copy the code