Home > Back-end >  Cannot use vibration in a Thread
Cannot use vibration in a Thread

Time:07-18

I'm trying to use the vibrator service inside a Thread class but when I do so, I have an error which says "Type mismatch: inferred type is String but Context was expected"

here is my code :

class myThread: Thread()  {
    override fun run() {
        var vibration = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        for(i in 1..5) {
            vibration.vibrate(100)
            Thread.sleep(1000)
        }
    }
}

It works in my mainActivity class but it doesn't in a Thread. Thank you in advance for any help.

CodePudding user response:

"It works in my mainActivity class but it doesn't in a Thread. "

getSystemService is defined in Activity class with the signature below.

public Object getSystemService(@ServiceName @NonNull String name) 

When you use same method name in any other class, you are using ContextCompat helper class which requires a context and serviceClass.

// ContextCompat.class
public static <T> T getSystemService(@NonNull Context context, @NonNull Class<T> serviceClass) 

You may change your MyThread class like below.

class MyThread(
  private val appContext: Context
) : Thread() {

    override fun run() {
      val vibrator = getSystemService(appContext, Vibrator::class.java) as Vibrator

      for (i in 1..5) {
        vibrator.vibrate(100)
        Thread.sleep(1000)
      }
    }
  }

// Or inject vibrator by constructor
class MyThread2(
  private val vibrator: Vibrator
) : Thread() {

  override fun run() {
      for (i in 1..5) {
          vibrator.vibrate(100)
          Thread.sleep(1000)
      }
  }

}   

CodePudding user response:

Vibrator service needs context to operate, if you are using myThread inside and activity or in a class with access to context, you can simply make the myThread an inner class like below and it should work.

inner class myThread: Thread()  {
    override fun run() {
        var vibration = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        for(i in 1..5) {
            vibration.vibrate(100)
            Thread.sleep(1000)
        }
    }
}
  • Related