I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
I use the following utils method:
Add the following permission to the AndroidManifest file
You can use overloaded methods in case if you wish to use different types of vibrations (patterns / indefinite) as suggested above.
should be added inside
<manifest>
tag and outside<application>
tag.Grant Vibration Permission
Before you start implementing any vibration code, you have to give your application the permission to vibrate:
Make sure to include this line in your AndroidManifest.xml file.
Import the Vibration Library
Most IDEs will do this for you, but here is the import statement if yours doesn't:
Make sure this in the activity where you want the vibration to occur.
How to Vibrate for a Given Time
In most circumstances, you'll be wanting to vibrate the device for a short, predetermined amount of time. You can achieve this by using the
vibrate(long milliseconds)
method. Here is a quick example:That's it, simple!
How to Vibrate Indefinitely
It may be the case that you want the device to continue vibrating indefinitely. For this, we use the
vibrate(long[] pattern, int repeat)
method:When you're ready to stop the vibration, just call the
cancel()
method:How to use Vibration Patterns
If you want a more bespoke vibration, you can attempt to create your own vibration patterns:
More Complex Vibrations
There are multiple SDKs that offer a more comprehensive range of haptic feedback. One that I use for special effects is Immersion's Haptic Development Platform for Android.
Troubleshooting
If your device won't vibrate, first make sure that it can vibrate:
Secondly, please ensure that you've given your application the permission to vibrate! Refer back to the first point.