I have this problem: I should vibrate the phone for 500ms *, 300ms of pause, 500ms * of vibration, 300ms of pause and finally 500ms * of vibration. I tried using Handler but unfortunately it's like they add up in one wait time. Is there a specific way to do all these operations sequentially and by putting a delay between them? A thousand thanks.
Time varies depending on many factors
val vibration = requireActivity().getSystemService(Context.VIBRATOR_SERVICE) as Vibrator Handler(Looper.getMainLooper()).postDelayed({ vibration.vibrate(code.code.duration1.toLong()) }, 600) Handler(Looper.getMainLooper()).postDelayed({ vibration.vibrate(code.code.duration2.toLong()) }, 2000) Handler(Looper.getMainLooper()).postDelayed({ vibration.vibrate(code.code.duration3.toLong()) id.setImageDrawable(AppCompatResources.getDrawable(requireActivity(), R.drawable.ic_play)) }, 3600)
CodePudding user response:
Instead of using Handler, which is now deprecated, use the Thread class, by doing something like this:
Thread{
// your code here
Thread.sleep(5000)
}.start()
This will wait for the input time to pass before running.
However, for a more useful way of doing this, you can use the Timer class. You can read about it and how to use it here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.concurrent/java.util.-timer/
This kind of timer allows you to run a function during a period of time, then stop, the start it again within another period of time.
CodePudding user response:
Try the below code, which is working for me perfectly.
fun Fragment.vibratePhone() {
val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
vibrator.vibrate(
VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK),
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setHapticChannelsMuted(false)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
} else {
vibrator.vibrate(
VibrationEffect.createOneShot(VIBRATION_TIME, VIBRATION_AMPLITUDE),
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
}
} else {
vibrator.vibrate(longArrayOf(0, 100, 50, 100, 50, 100), -1)
}
}
In the above code, you will see that,
- 0 means delay
- 100 means vibrate for 100ms
- 50 means delay
- 100 means vibrate for 100ms and so on.
- Repetition: at last -1 means vibration will happen in the pattern you have defined and won't repeat else define several times you want to repeat it.