首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作系统3上的VibratorManager和安卓花栗鼠2021.2.1 Beta

操作系统3上的VibratorManager和安卓花栗鼠2021.2.1 Beta
EN

Stack Overflow用户
提问于 2022-04-05 03:00:55
回答 2查看 114关注 0票数 1
代码语言:javascript
复制
    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()

上面的代码会导致仿真器和三星Galaxy 4-磨损OS3.2-Android 11上出现一个空白屏幕。

我在这里复制了几个答案的代码。当我注释掉上述代码时,我的应用程序在模拟器和上述手表上运行得很好。

  1. 这里有人最近写了一个与VibratorManager有关的代码吗?
  2. 是我的等级吗?
  3. ,我应该使用最新的Beta版本的Android吗?
  4. 还有另一种方式来完成我的任务,不是通知用户,而是在不需要用户输入的情况下振动手表?

<代码>G 210

谢谢

EN

回答 2

Stack Overflow用户

发布于 2022-04-05 14:19:51

Access application context in companion object in kotlin

上面的柱子修好了我的窃听器。这就是我所做的。

  1. In MainActivity,我添加了他的代码:

代码语言:javascript
复制
init {
    instance = this
}

companion object {
    private var instance: MainActivity? = null

    fun applicationContext() : Context {
        return instance!!.applicationContext
    }
}

  1. ,在我的函数中,我从他那里添加了以下代码:

val context: Context = MainActivity.applicationContext()

票数 1
EN

Stack Overflow用户

发布于 2022-05-01 06:06:03

下面的代码片段适用于我

声明变量

代码语言:javascript
复制
    private lateinit var mVibrator: Vibrator
    private lateinit var vibrationEffectSingle : VibrationEffect

初始化(以onCreate()表示)

代码语言:javascript
复制
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)
}

使用

代码语言:javascript
复制
                mVibrator.vibrate(vibrationEffectSingle)

在宣言中

代码语言:javascript
复制
    <uses-permission android:name="android.permission.VIBRATE" />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71745877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档