【问题标题】:How to make an Android device vibrate? with different frequency?如何让安卓设备振动?频率不同?
【发布时间】:2023-03-16 02:33:01
【问题描述】:

我编写了一个 Android 应用程序。现在,我想让设备在某个动作发生时振动。我该怎么做?

【问题讨论】:

    标签: java android kotlin vibration android-vibration


    【解决方案1】:

    试试:

    import android.os.Vibrator;
    ...
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    // Vibrate for 500 milliseconds
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        //deprecated in API 26 
        v.vibrate(500);
    }
    

    注意:

    不要忘记在 AndroidManifest.xml 文件中包含权限:

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

    【讨论】:

    • 有没有办法取消所有手机的震动?谢谢!
    • @joshsvoss 这是 500 毫秒,也就是半秒。查看谷歌文档。 developer.android.com/reference/android/os/Vibrator.html
    • 它给了我:上下文无法解析或不是字段..?!有什么问题
    • 振动现已弃用。请改用 Hitesh Sahu 的解决方案。
    • 此方法在 API 级别 26 中已弃用。请改用 vibrate(VibrationEffect)
    【解决方案2】:

    授予振动权限

    在您开始实施任何振动代码之前,您必须为您的应用程序授予振动权限:

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

    确保在您的 AndroidManifest.xml 文件中包含这一行。

    导入振动库

    大多数 IDE 都会为您执行此操作,但如果您的 IDE 不这样做,这里是导入语句:

     import android.os.Vibrator;
    

    确保在您希望发生振动的活动中这样做。

    如何在给定时间内振动

    在大多数情况下,您会希望在预定的短时间内振动设备。您可以使用vibrate(long milliseconds) 方法来实现此目的。这是一个简单的例子:

    // Get instance of Vibrator from current Context
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
    // Vibrate for 400 milliseconds
    v.vibrate(400);
    

    就是这样,简单!

    如何无限期振动

    您可能希望设备无限期地继续振动。为此,我们使用vibrate(long[] pattern, int repeat) 方法:

    // Get instance of Vibrator from current Context
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
    // Start without a delay
    // Vibrate for 100 milliseconds
    // Sleep for 1000 milliseconds
    long[] pattern = {0, 100, 1000};
    
    // The '0' here means to repeat indefinitely
    // '0' is actually the index at which the pattern keeps repeating from (the start)
    // To repeat the pattern from any other point, you could increase the index, e.g. '1'
    v.vibrate(pattern, 0);
    

    当您准备好停止振动时,只需调用cancel() 方法:

    v.cancel();
    

    如何使用振动模式

    如果您想要更定制的振动,您可以尝试创建自己的振动模式:

    // Get instance of Vibrator from current Context
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
    // Start without a delay
    // Each element then alternates between vibrate, sleep, vibrate, sleep...
    long[] pattern = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
    
    // The '-1' here means to vibrate once, as '-1' is out of bounds in the pattern array
    v.vibrate(pattern, -1);
    

    更复杂的振动

    有多个 SDK 可提供更全面的触觉反馈。我用于特殊效果的一个是Immersion's Haptic Development Platform for Android

    疑难解答

    如果您的设备不会振动,请先确保它可以振动:

    // Get instance of Vibrator from current Context
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    
    // Output yes if can vibrate, no otherwise
    if (v.hasVibrator()) {
        Log.v("Can Vibrate", "YES");
    } else {
        Log.v("Can Vibrate", "NO");
    }
    

    其次,请确保您已授予应用程序振动的权限!回到第一点。

    【讨论】:

    • 很好的答案,虽然我会警惕无限期地播放振动。使用此功能请自行负责!
    • 很好的答案,但有一件事。当你说'这里的'0'意味着无限重复'时,虽然是真的,但有点误导。这个数字是重复时模式将开始的模式数组的索引。
    • @aaronvargas 公平点,尽管这超出了大多数人试图实现的范围。我做了一个简单的解释:)
    • @Liam George Betsworth 即使手机处于静音模式,我如何振动?请。
    • 沉浸式链接已关闭,我在 archive.org 上找不到它:(
    【解决方案3】:

    Android-O(API 8.0) 已弃用 Update 2017 vibrate(interval) 方法

    要支持所有 Android 版本,请使用此方法。

    // Vibrate for 150 milliseconds
    private void shakeItBaby() {
        if (Build.VERSION.SDK_INT >= 26) {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            ((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(150);
        }
    }
    

    科特林:

    // Vibrate for 150 milliseconds
    private fun shakeItBaby(context: Context) {
        if (Build.VERSION.SDK_INT >= 26) {
            (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE))
        } else {
            (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(150)
        }
    }
    

    【讨论】:

    • 我们不需要 Vibration 的运行时权限。振动不是一个危险的许可,所以它只能在清单中声明。 [developer.android.com/guide/topics/permissions/…
    • @BugsHappen 文档已移动。将更新或删除它。
    • 我唯一要补充的是,如果您在 Activity 中使用它并且没有特定的 Context 变量,则将 getSystemService 替换为 this.getContext().getSystemService
    • 你先生赢得了赞成票,因为这个功能名称,touché
    【解决方案4】:

    以上答案很完美。但是,我想在按钮单击时准确地振动我的应用程序两次,而这里缺少这个小信息,因此为像我这样的未来读者发布。 :)

    我们必须按照上面提到的方式进行,唯一的变化是振动模式如下,

    long[] pattern = {0, 100, 1000, 300};
    v.vibrate(pattern, -1); //-1 is important
    

    这将准确地振动 两次。我们已经知道

    1. 0 代表延迟
    2. 100 第一次说振动 100 毫秒
    3. 接下来是 1000 毫秒的 延迟
    4. 然后再次发布振动 300 毫秒

    人们可以交替提及延迟和振动(例如 0、100、1000、300、1000、300 表示 3 次振动等等),但请记住 @Dave 的话,负责任地使用它。 :)

    另外请注意,repeat 参数设置为 -1,这意味着振动将发生完全如模式中所述。 :)

    【讨论】:

    • 为什么 -1 意味着振动会完全按照模式中提到的那样发生?谢谢!
    • @Rich 请参考我的回答。 “-1”是第一次遵循该模式后,振动将尝试重复的索引。 '-1' 超出范围,因此振动不会重复。
    • @Rich - Liam George Betsworth 是正确的。 Android 文档说 - 要使模式重复,请将索引传递到开始重复的模式数组中,或者 -1 以禁用重复。链接 - developer.android.com/reference/android/os/…, int)
    【解决方案5】:

    未经许可振动

    如果您想简单地振动设备一次以提供有关用户操作的反馈。您可以使用ViewperformHapticFeedback() 函数。这不需要在清单中声明VIBRATE 权限。

    在您项目的 Utils.kt 等常见类中使用以下函数作为顶级函数:

    /**
     * Vibrates the device. Used for providing feedback when the user performs an action.
     */
    fun vibrate(view: View) {
        view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
    }
    

    然后在FragmentActivity 中的任何位置使用它,如下所示:

    vibrate(requireView())
    

    就这么简单!

    【讨论】:

    • 确保添加 HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING 标志,使其适用于所有设备。
    【解决方案6】:

    在我的第一次实施中,我很难理解如何做到这一点 - 请确保您具备以下条件:

    1) 您的设备支持振动(我的三星平板电脑无法正常工作,因此我不断重新检查代码 - 原始代码在我的 CM 触摸板上完美运行

    2) 您已在 AndroidManifest.xml 文件中的应用程序级别上方声明,以授予代码运行权限。

    3) 已将以下两项与其他导入一起导入您的 MainActivity.java: 导入android.content.Context; 导入android.os.Vibrator;

    4) 调用您的振动(已在此线程中进行了广泛讨论) - 我在一个单独的函数中完成了它,并在其他点的代码中调用了它 - 取决于您想要使用什么来调用您可能需要图像的振动(Android: long click on a button -> perform actions) 或按钮侦听器,或 XML 中定义的可点击对象 (Clickable image - android):

     public void vibrate(int duration)
     {
        Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibs.vibrate(duration);    
     }
    

    【讨论】:

      【解决方案7】:

      Kotlin 更新以提高类型安全性

      将它用作项目的某些通用类中的顶级函数,例如 Utils.kt

      // Vibrates the device for 100 milliseconds.
      fun vibrateDevice(context: Context) {
          val vibrator = getSystemService(context, Vibrator::class.java)
          vibrator?.let {
              if (Build.VERSION.SDK_INT >= 26) {
                  it.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
              } else {
                  @Suppress("DEPRECATION")
                  it.vibrate(100)
              }
          }
      }
      

      然后在代码中的任意位置调用它,如下所示:

      vibrateDevice(requireContext())
      

      说明

      使用Vibrator::class.java 比使用String 常量更安全。

      我们使用let { } 检查vibrator 的可空性,因为如果振动不适用于设备,vibrator 将是null

      可以在 else 子句中禁止弃用,因为警告来自较新的 SDK。

      我们不需要在运行时请求许可才能使用振动。但我们需要在AndroidManifest.xml 中声明如下:

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

      【讨论】:

        【解决方案8】:

        模式/波形振动:

        import android.os.Vibrator;
        ...
        // Pause for 500ms, vibrate for 500ms, then start again
        private static final long[] VIBRATE_PATTERN = { 500, 500 };
        
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // API 26 and above
            mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
        } else {
            // Below API 26
            mVibrator.vibrate(VIBRATE_PATTERN, 0);
        }
        

        加号

        AndroidManifest.xml中的必要权限:

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

        【讨论】:

        • 其实这个会暂停500ms,震动500ms然后重新开始
        【解决方案9】:
        <uses-permission android:name="android.permission.VIBRATE"/>
        

        应该添加在&lt;manifest&gt;标签内和&lt;application&gt;标签外。

        【讨论】:

          【解决方案10】:

          我使用以下 utils 方法:

          public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
              Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
              vibrator.vibrate(vibrateMilliSeconds);
          }
          

          在AndroidManifest文件中添加以下权限

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

          如果您希望使用上面建议的不同类型的振动(模式/无限期),您可以使用重载方法。

          【讨论】:

            【解决方案11】:

            以上答案非常正确,但我给出了一个简单的步骤:

             private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };
            
              public void longVibrate(View v) 
              {
                 vibrateMulti(THREE_CYCLES);
              }
            
              private void vibrateMulti(long[] cycles) {
                  NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
                  Notification notification = new Notification();
            
                  notification.vibrate = cycles; 
                  notificationManager.notify(0, notification);
              }
            

            然后在你的xml文件中:

            <button android:layout_height="wrap_content" 
                    android:layout_width ="wrap_content" 
                    android:onclick      ="longVibrate" 
                    android:text         ="VibrateThrice">
            </button>
            

            这就是easiest 的方式。

            【讨论】:

              【解决方案12】:

              使用这个:

              import android.os.Vibrator;
                   ...
                   Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                   // Vibrate for 1000 milliseconds
                   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                          v.vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
                   }else{
                   //deprecated in API 26 
                          v.vibrate(1000);
                   }
              

              注意:

              不要忘记在 AndroidManifest.xml 文件中包含权限:

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

              【讨论】:

                【解决方案13】:

                您可以振动设备及其工作

                   Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                           v.vibrate(100);
                

                需要权限,但不需要运行时权限

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

                【讨论】:

                • 此解决方案已弃用
                猜你喜欢
                • 1970-01-01
                • 2011-05-03
                • 1970-01-01
                • 2018-10-06
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多