11

この私のパターンのように同じパターンを5回振動させる方法を誰か教えてください

long[] pattern = { 0, 200, 500 };

このパターンを5回繰り返したい

Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern , 5);
4

9 に答える 9

22

私は解決策を見つけました、それは非常に簡単でした:

long[] pattern = { 0, 100, 500, 100, 500, 100, 500, 100, 500, 100, 500};
vibrator.vibrate(pattern , -1);
于 2011-05-12T10:39:30.700 に答える
4

以下は私にとってはうまくいきます:

if(vibration_enabled) {
    final Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    if(v.hasVibrator()) {
        final long[] pattern = {0, 1000, 1000, 1000, 1000};
        new Thread(){
            @Override
            public void run() {
                for(int i = 0; i < 5; i++){ //repeat the pattern 5 times
                    v.vibrate(pattern, -1);
                    try {
                       Thread.sleep(4000); //the time, the complete pattern needs
                    } catch (InterruptedException e) {
                        e.printStackTrace();  
                    }
                }
            }
        }.start();
    }
}

vibrate メソッドは振動を開始するだけで、実行されるまで待機しません。

于 2013-09-09T22:36:17.423 に答える
3

あなたのコードでうまくいくはずです。ファイル<uses-permission android:name="android.permission.VIBRATE"/> にあることを確認してください 。AndroidManifest.xml

于 2011-05-04T07:57:55.803 に答える
0

1 つのトリックを適用できます。必要な反復回数に基づいてパターンを動的に構築するだけです。

private long[] createVibrationPattern(long[] oneShotPattern, int repeat) {
    long[] repeatPattern = new long[oneShotPattern.length * repeat];
    System.arraycopy(oneShotPattern, 0, repeatPattern, 0, oneShotPattern.length);
    for (int count = 1; count < repeat; count++) {
        repeatPattern[oneShotPattern.length * count] = 500; // Delay in ms, change whatever you want for each repition
        System.arraycopy(oneShotPattern, 1, repeatPattern, oneShotPattern.length * count + 1, oneShotPattern.length - 1);
    }
    return repeatPattern;
}

次に、以下のように呼び出します

long[] pattern = { 0, 200, 500 };
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(createVibrationPattern(pattern , 2);

OUTPUTパターンは 0, 200, 500, 500 , 0, 200, 500 になります

于 2020-07-17T13:06:35.920 に答える
0

これが私がやった方法です。発信者が振動させたい回数に基づいて、タイミング配列を動的に生成します。ループでは、0 % 2 を避けるために 1 から開始して、最後に余分な無駄な遅延を引き起こします。

private void vibrate(int times)
{
    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        ArrayList<Long> timings = new ArrayList();

        timings.add(0L);

        for(int i = 1; i <= times; i ++)
        {

            if(i%2==0)
                timings.add(0L);

            timings.add(250L);


        }

        long[] arrTimings = new long[timings.size()];

        for(int j = 0; j < timings.size(); j++)
        {
            arrTimings[j] = timings.get(j);
        }

        vibrator.vibrate(VibrationEffect.createWaveform(arrTimings, -1));
    }
}
于 2019-02-13T21:07:14.717 に答える