不能在线程中使用振动



我试图在线程类中使用振动器服务,但当我这样做时,我有一个错误,说"类型不匹配:推断类型是字符串,但上下文是预期的">

下面是我的代码:
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)
}
}
}

它在我的mainActivity类中工作,但在线程中不起作用。提前感谢您的帮助。

"它在我的mainActivity类中工作,但它不在线程中。">

getSystemService在Activity类中定义,签名如下。

public Object getSystemService(@ServiceName @NonNull String name) 

当使用相同的方法名称时在任何其他类中,您都使用ContextCompathelper类,它需要上下文和serviceClass。

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

你可以像下面这样改变你的MyThread类。

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)
}
}
}