Home >Java >javaTutorial >How Can I Control Device Vibrations in Android?

How Can I Control Device Vibrations in Android?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 19:58:10614browse

How Can I Control Device Vibrations in Android?

Controlling Device Vibrations in Android

In Android development, providing haptic feedback to users through device vibrations can enhance the user experience. Here's how you can implement this functionality:

Making the Device Vibrate

To initiate vibrations in an Android device, you'll need to access the Vibrator class and its methods. The following code snippet demonstrates how to do this:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Remember, for successful vibration functionality, ensure you include the necessary permission in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.VIBRATE"/>

The above is the detailed content of How Can I Control Device Vibrations in Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn