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

How Can I Control Device Vibrations in Android?

Mary-Kate Olsen
Release: 2024-12-01 19:58:10
Original
625 people have browsed it

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);
}
Copy after login

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

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

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template