如何使Android设备振动?

本文翻译自:How to make an Android device vibrate?

I wrote an Android application. 我写了一个Android应用程序。 Now, I want to make the device vibrate when a certain action occurs. 现在,我想让设备在发生某些动作时振动。 How can I do this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/wX7S/如何使Android设备振动


#2楼

Try: 尝试:

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

Note: 注意:

Don't forget to include permission in AndroidManifest.xml file: 不要忘记在AndroidManifest.xml文件中包含权限:

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

#3楼

Grant Vibration Permission 授予振动许可

Before you start implementing any vibration code, you have to give your application the permission to vibrate: 在开始实施任何振动代码之前,您必须授予应用程序振动的权限:

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

Make sure to include this line in your AndroidManifest.xml file. 确保在AndroidManifest.xml文件中包含此行。

Import the Vibration Library 导入振动库

Most IDEs will do this for you, but here is the import statement if yours doesn't: 大多数IDE都会为您执行此操作,但是如果您没有,则这是import语句:

 import android.os.Vibrator;

Make sure this in the activity where you want the vibration to occur. 在要发生振动的活动中确保执行此操作。

How to Vibrate for a Given Time 如何在给定的时间内振动

In most circumstances, you'll be wanting to vibrate the device for a short, predetermined amount of time. 在大多数情况下,您需要在预定的短时间内振动设备。 You can achieve this by using the vibrate(long milliseconds) method. 您可以通过使用vibrate(long milliseconds)方法来实现。 Here is a quick example: 这是一个简单的示例:

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 400 milliseconds
v.vibrate(400);

That's it, simple! 就是这样,很简单!

How to Vibrate Indefinitely 如何无限振动

It may be the case that you want the device to continue vibrating indefinitely. 您可能希望设备无限期地继续振动。 For this, we use the vibrate(long[] pattern, int repeat) method: 为此,我们使用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);

When you're ready to stop the vibration, just call the cancel() method: 当您准备停止振动时,只需调用cancel()方法即可:

v.cancel();

How to use Vibration Patterns 如何使用振动模式

If you want a more bespoke vibration, you can attempt to create your own vibration patterns: 如果要定制振动,可以尝试创建自己的振动模式:

// 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);

More Complex Vibrations 更复杂的振动

There are multiple SDKs that offer a more comprehensive range of haptic feedback. 有多个SDK提供了更全面的触觉反馈。 One that I use for special effects is Immersion's Haptic Development Platform for Android . 我用于特殊效果的一个是Immersion的Android触觉开发平台

Troubleshooting 故障排除

If your device won't vibrate, first make sure that it can vibrate: 如果您的设备不会振动,请首先确保它可以振动:

// 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");
}

Secondly, please ensure that you've given your application the permission to vibrate! 其次,请确保您已授予您的应用振动的权限! Refer back to the first point. 回到第一点。


#4楼

I struggled understanding how to do this on my first implementation - make sure you have the following: 我很难理解如何在第一个实现中执行此操作-确保您具有以下条件:

1) Your device supports vibration (my Samsung tablet did not work so I kept re-checking the code - the original code worked perfectly on my CM Touchpad 1)您的设备支持振动(我的三星平板电脑无法正常工作,因此我不断检查代码-原始代码在CM触摸板上可正常使用

2) You have declared above the application level in your AndroidManifest.xml file to give the code permission to run. 2)您已在AndroidManifest.xml文件中的应用程序级别之上声明,以赋予代码运行权限。

3) Have imported both of the following in to your MainActivity.java with the other imports: import android.content.Context; 3)已将以下两项与其他项导入到您的MainActivity.java中:import android.content.Context; import android.os.Vibrator; 导入android.os.Vibrator;

4) Call your vibration (discussed extensively in this thread already) - I did it in a separate function and call this in the code at other points - depending on what you want to use to call the vibration you may need an image ( Android: long click on a button -> perform actions ) or button listener, or a clickable object as defined in XML ( Clickable image - android ): 4)调用您的振动(已经在此线程中进行了广泛讨论)-我在一个单独的函数中进行了此操作,并在其他点的代码中调用了它-根据您要用来调用振动的内容,您可能需要一张图片( Android:长按按钮->执行动作 )或按钮侦听器,或XML中定义的可点击对象( Clickable image-android ):

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

#5楼

Above answers are perfect. 以上答案是完美的。 However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. 但是,我想在单击按钮时使我的应用程序精确振动两次,因此这里缺少这些小信息,因此请像我这样的未来读者发布。 :) :)

We have to follow as mentioned above and the only change will be in the vibrate pattern as below, 如上所述,我们必须遵循,唯一的变化就是振动模式如下,

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

This will exactly vibrate twice. 这将恰好振动两次。 As we already know 0 is for delay, 100 says vibrate for 100MS for the first time, next comes delay of 1000MS and post that vibrate again for 300MS. 我们已经知道0是延迟,100表示​​第一次振动100MS,接着是1000MS的延迟,然后再次振动300MS。

One can go on and on mentioning delay and vibration alternatively (eg 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. 一个人可以继续提到延迟和振动(例如0、100、1000、300、1000、300表示3次振动等等。),但请记住@Dave的话负责任地使用它。 :) :)

Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. 在此还要注意,repeat参数设置为-1,这意味着振动将完全按照模式中所述发生。 :) :)


#6楼

Above answer is very correct but I'm giving an easy step to do it: 上面的答案是非常正确的,但我给出了一个简单的步骤:

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

And then in your xml file: 然后在您的xml文件中:

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

That's the easiest way. 那是最简单的方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值