androidkotlinnativedelayvibration

Is there a way to make instructions with 300ms between them?


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)

Solution

  • 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,