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
Above answer is very correct but I'm giving an easy step to do it:
And then in your xml file:
That's the easiest way.
I struggled understanding how to do this on my first implementation - make sure you have the following:
1) Your device supports vibration (my Samsung tablet did not work so I kept re-checking the code - the original code worked perfectly on my CM Touchpad
2) You have declared above the application level in your AndroidManifest.xml file to give the code permission to run.
3) Have imported both of the following in to your MainActivity.java with the other imports: import android.content.Context; import android.os.Vibrator;
4) Call your vibration (discussed extensively in this thread already) - I did it in a separate function and call this in the code at other points - depending on what you want to use to call the vibration you may need an image (Android: long click on a button -> perform actions) or button listener, or a clickable object as defined in XML (Clickable image - android):
Use this:
Note:
Don't forget to include permission in AndroidManifest.xml file:
Above answers are perfect. However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. :)
We have to follow as mentioned above and the only change will be in the vibrate pattern as below,
This will exactly vibrate twice. As we already know 0 is for delay, 100 says vibrate for 100MS for the first time, next comes delay of 1000MS and post that vibrate again for 300MS.
One can go on and on mentioning delay and vibration alternatively (e.g. 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. :)
Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. :)
Try:
Note:
Don't forget to include permission in AndroidManifest.xml file:
Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)
To support all Android versions use this method.
Kotlin: