Android 9上的震动

时间:2019-07-01 15:00:46

标签: java android

我有这种振动方法,可使我的应用程序完全按照我的手机振动要求(Android 6 API23)。

但是,当我的朋友在他的手机(Android 9)上尝试操作时,它无法正常工作。它不断以错误的方式振动,他甚至无法使用应用程序中的按钮将其关闭。

如何使振动在更新版本的Android上完全相同?

long[] pattern = { 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};

这是振动代码

v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d("VIBRATE ===>", "I AM VIBRATING");

               // v.vibrate(VibrationEffect.createWaveform(pattern, 0)); This did not work

            } else {
                Log.d("VIBRATE ====>", "I AM VIBRATING");


                v.vibrate(pattern , 0); //This do work on Android 6
            }

这是停止振动的方法。 (同样适用于Android 6)

public static void stopVibration() {
        v.cancel();

}

编辑我的尝试

所以我希望它振动1秒,暂停1秒,振动1秒,依此类推,直到按下按钮。您是否认为此代码适用于Android 9(或者我想API> 26)?

 long[] mVibratePattern = new long[]{ 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
 int[] mAmplitudes = new int[]{0, 255, 255, 255, 255, 255, 255, 255};



            v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d("VIBRATE ===>", "I AM VIBRATING");


                    VibrationEffect effect = VibrationEffect.createWaveform(mVibratePattern, mAmplitudes, 0); //Will this work on Android 9?
                    v.vibrate(effect);


            } else {
                Log.d("VIBRATE ====>", "I AM VIBRATING");


                v.vibrate(pattern , 0); //This do work on Android 6
            }

2 个答案:

答案 0 :(得分:0)

所以我得到了Android 9手机,这使振动在Android 9上也一样。

long[] pattern = { 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
int[] mAmplitudes = new int[]{0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0};

  v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.d("VIBRATE ===>", "I AM VIBRATING");


                    VibrationEffect effect = VibrationEffect.createWaveform(pattern, mAmplitudes, 0); //This do work on Android 9
                    v.vibrate(effect);




            } else {
                Log.d("VIBRATE ====>", "I AM VIBRATING");


                v.vibrate(pattern , 0); //This do work on Android 6
            }

答案 1 :(得分:0)

Try this once
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);
     }