Android Studio Java获取系统服务错误

k2fxgqgv  于 2023-01-17  发布在  Android
关注(0)|答案(1)|浏览(142)

仅供参考,我开始学习java还不到2个月,所以我是一个初学者。我正在尝试找出当用户点击选项时如何应用振动。但是,getSystemService由于某种原因是红色的,我做错了什么,需要修改什么?(我导入了vibration,并在manifest xml中为vibration编写了uses-permission。)我尝试了其他人的建议,但无论我尝试getSystemService总是红色...以下是我的代码:

public void hospital1select1() {
      h1.character.setVisibility(View.INVISIBLE);
      h1.text.setVisibility(View.INVISIBLE);
      showButton();
      h1.choice1.setVisibility(View.INVISIBLE);
      h1.choice4.setVisibility(View.INVISIBLE);
      h1.choice2.setText("");
      h1.choice3.setText("");

      h1.choice1.findViewById(R.id.choice1);
      h1.choice1.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view){
  Vibrator vibrator = (Vibrator)
  getSystemService(Context.VIBRATOR_SERVICE);
              vibrator.vibrate(400);
          }
      });

      c2 = "h110a";
      c3 = "h110b";
  }
mwngjboj

mwngjboj1#

步骤1

Manifest中添加权限

<uses-permission android:name="android.permission.VIBRATE" />

步骤2

将这三行作为导入添加到java_file的顶部,例如MainActivity.java

import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager

步骤3

在您的onClickListener中,复制/粘贴此内容

Vibrator vibrator;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
    VibratorManager vibratorManager = (VibratorManager) getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
    vibrator = vibratorManager.getDefaultVibrator();
} else {
    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    vibrator.vibrate(VibrationEffect.createOneShot(400, VibrationEffect.DEFAULT_AMPLITUDE));
else
    vibrator.vibrate(400);

相关问题