¿Cómo hacer vibrar un dispositivo Android? con diferente frecuencia?
Escribí una aplicación para Android. Ahora quiero hacer que el dispositivo vibre cuando ocurra una determinada acción. ¿Cómo puedo hacer esto?
Intentar:
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);
}
Nota:
No olvide incluir el permiso en el archivo AndroidManifest.xml:
<uses-permission android:name="android.permission.VIBRATE"/>
Conceder permiso de vibración
Antes de comenzar a implementar cualquier código de vibración, debes darle permiso a tu aplicación para que vibre:
<uses-permission android:name="android.permission.VIBRATE"/>
Asegúrese de incluir esta línea en su archivo AndroidManifest.xml.
Importar la biblioteca de vibraciones
La mayoría de los IDE harán esto por usted, pero aquí está la declaración de importación si el suyo no lo hace:
import android.os.Vibrator;
Asegúrate de esto en la actividad en la que deseas que se produzca la vibración.
Cómo vibrar durante un tiempo determinado
En la mayoría de las circunstancias, querrás hacer vibrar el dispositivo durante un período de tiempo corto y predeterminado. Puedes lograr esto usando el vibrate(long milliseconds)
método. Aquí hay un ejemplo rápido:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
v.vibrate(400);
¡Eso es todo, sencillo!
Cómo vibrar indefinidamente
Puede darse el caso de que quieras que el dispositivo siga vibrando indefinidamente. Para ello utilizamos el vibrate(long[] pattern, int repeat)
método:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, 0);
Cuando estés listo para detener la vibración, simplemente llama al cancel()
método:
v.cancel();
Cómo utilizar patrones de vibración
Si desea una vibración más personalizada, puede intentar crear sus propios patrones de vibración:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
// The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
v.vibrate(pattern, -1);
Vibraciones más complejas
Existen varios SDK que ofrecen una gama más completa de retroalimentación háptica. Una que uso para efectos especiales es la plataforma de desarrollo háptico de Immersion para Android .
Solución de problemas
Si su dispositivo no vibra, primero asegúrese de que pueda vibrar:
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Output yes if can vibrate, no otherwise
if (v.hasVibrator()) {
Log.v("Can Vibrate", "YES");
} else {
Log.v("Can Vibrate", "NO");
}
En segundo lugar, asegúrese de haberle dado permiso a su aplicación para vibrar. Vuelva al primer punto.
El método de vibración (intervalo) de la actualización 2017 está obsoleto con Android-O (API 8.0)
Para admitir todas las versiones de Android, utilice este método.
// Vibrate for 150 milliseconds
private void shakeItBaby() {
if (Build.VERSION.SDK_INT >= 26) {
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
}
}
Kotlin:
// Vibrate for 150 milliseconds
private fun shakeItBaby(context: Context) {
if (Build.VERSION.SDK_INT >= 26) {
(context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
(context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
}
}