'VibratorManager on Wear OS 3 and Android Chipmunk 2021.2.1 Beta
val context = ApplicationProvider.getApplicationContext<Application>()
val vibratorManager = context?.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
val vibrator = vibratorManager.getDefaultVibrator()
if ((drawCount == 240) or (drawCount == 60)){
vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
} else if ((drawCount <= 60) and (drawCount.mod(5) == 0)){
vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
}
vibrator.cancel()
vibratorManager.cancel()
The code above causes a blank screen on the Emulator and on Samsung Galaxy Watch 4 - Wear OS 3.2 - Android 11.
I copied the code from several answers here. When I comment out the above code, my app runs great on the Emulator and on the said watch.
- Has anyone here written a code relating to the VibratorManager lately?
- Is it my Gradle?
- Should I use the latest Beta version of the Android Studio?
- Is there another way to accomplish my task which is NOT to notify the user but to vibrate the watch without requiring a user input?
Thanks
Solution 1:[1]
Access application context in companion object in kotlin
The post above fixed my bug. Here is what I did.
- In the MainActivity, I added his code:
init {
instance = this
}
companion object {
private var instance: MainActivity? = null
fun applicationContext() : Context {
return instance!!.applicationContext
}
}
- And on my function, I added this code from him:
val context: Context = MainActivity.applicationContext()
Solution 2:[2]
The following code snippet works for me
Declare variables
private lateinit var mVibrator: Vibrator
private lateinit var vibrationEffectSingle : VibrationEffect
Initialisation (in onCreate())
if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// VibratorManager was only added on API level 31 release.
val vibratorManager = getSystemService(VIBRATOR_MANAGER_SERVICE) as VibratorManager
mVibrator = vibratorManager.defaultVibrator
} else {
// backward compatibility for Android API < 31
mVibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
}
vibrationEffectSingle = VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)
}
Use
mVibrator.vibrate(vibrationEffectSingle)
In the Manifest
<uses-permission android:name="android.permission.VIBRATE" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TofferJ |
Solution 2 | RatherBeSailing |