Search code examples
javaandroidvibrationpulse

Having trouble pulsing vibrator


I'm trying to implement a feature into my app where it can pulse the vibrator. The user can change 3 things, the vibration strength, pulse length, and time between pulses, using sliders.

I was thinking of some code like:

for(i=0; i<(pulse length * whatever)+(pulse gap * whatever); i+=1){
pattern[i]=pulse length*i;
patern[i+1]=pulse gap;

However, when I use this code (when its done properly, thats just a quick example) it crashes the app. Also, when I change the vibration strength (which does work) I have to restart the service for the strength to change. The way I change the strength is by altering the time the vibrator turns on ands turns off for in a pattern.

This is the code I use for detecting how the phone should vibrate (the code in here is a little different to what I would prefer):

if (rb == 3){
    z.vibrate(constant, 0);
} else if (rb == 2){
     smooth[0]=0;
     for (int i=1; i<100; i+=2){
           double angle = (2.0 * Math.PI * i) / 100;
           smooth[i] = (long) (Math.sin(angle)*127);
           smooth[i+1]=10;
     }
     z.vibrate(smooth, 0);
} else if (rb == 1){
     sharp[0]=0;
     for(int i=0; i<10; i+=2){
            sharp[i] = s*pl;
            sharp[i+1] = s+pg;
     }
     z.vibrate(sharp, 0);
}
} else {
        z.cancel();
}

If anyone's able to point me in the direction of some code that can do this, or how I can make it work, I would appreciate it very much.


Solution

  • The only guess I have is that you are receiving an ArrayIndexOutOfBounds error.

    If so, you need to define the length of your long arrays before trying to fill them.

    long[] OutOfBounds = new long[];
    OutOfBounds[0] = 100;
    // this is an error, it's trying to access something that does not exist.
    
    long[] legit = new long[3];
    legit[0] = 0;
    legit[1] = 500;
    legit[2] = 1000;
    // legit[3] = 0; Again, this will give you an error. 
    

    vibrate() is a smart function though. Neither of these examples throw an error:

    v.vibrate(legit, 0);
    // vibrate() combines both legit[0] + legit[2] for the 'off' time
    
    long tooLegit = new long[100];
    tooLegit[0] = 1000;
    tooLegit[1] = 500;
    tooLegit[10] = 100;
    tooLegit[11] = 2000;
    v.vibrate(tooLegit, 0);
    // vibrate() skips over the values you didn't define, ie long[2] = 0, long[3] = 0, etc
    

    Hope that helps.