How to make an Android device vibrate?

后端 未结 13 1729
长发绾君心
长发绾君心 2020-11-22 15:47

I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?

相关标签:
13条回答
  • 2020-11-22 16:22

    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.

    Import the Vibration Library

    Most IDEs will do this for you, but here is the import statement if yours doesn't:

     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. 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:

    // 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:

    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. One that I use for special effects is Immersion's Haptic Development Platform for 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.

    0 讨论(0)
  • 2020-11-22 16:25

    Update 2017 vibrate(interval) method is deprecated with Android-O(API 8.0)

    To support all Android versions use this method.

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

    Kotlin:

    // 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)
        }
    }
    
    0 讨论(0)
  • 2020-11-22 16:28

    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:

    <uses-permission android:name="android.permission.VIBRATE"/>
    
    0 讨论(0)
  • 2020-11-22 16:29

    Vibrating in Patterns/Waves:

    import android.os.Vibrator;
    ...
    // Vibrate for 500ms, pause 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);
    }
    

    Plus

    The necessary permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.VIBRATE"/>
    
    0 讨论(0)
  • 2020-11-22 16:31

    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:

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

    That's the easiest way.

    0 讨论(0)
  • 2020-11-22 16:34

    Vibrate without using permission

    If you want to simply vibrate the device once to provide a feedback on a user action. You can use performHapticFeedback() function of a View. This doesn't need the VIBRATE permission to be declared in the manifest.

    Use the following function as a top level function in some common class like Utils.kt of your project:

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

    And then use it anywhere in your Fragment or Activity as following:

    vibrate(requireView())
    

    Simple as that!

    0 讨论(0)
提交回复
热议问题