Oriol
Oriol

Reputation: 13

Android Vibration Crash

I want to add a vibration feedback for a game i'm developing, together a music play, like "winner" and a vibrate pattern.

The problem is that when I add the vibrate sentences, my app crashes.

For example:

 private void Down()
  {
    soundM.playSound(Sound.SOUND_NEWINTENT);

    for (int i=0 ; i<8 ; i++) {
      for (int j=0 ; j<12 ; j++) {
        if (Play[i][j] != null) {
          Play[i][j].moveDown();

          if (Play[i][j].getSpritePosition().y>=380) {
            Sprite.updateState(Sprite.STATE_GAME_LOST);
            endOfGame = true;

            soundM.playSound(Sound.SOUND_LOST);
            vib = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); 
            vib.vibrate(500); 

          }
        }
      }
    }

It is not inside an activity, so I can't implement something like this Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE), because it is an activity statement. I tried to declare public Vibrator vib; and then implement the code I showed above, but when the game lost is recived the application crashes.

I also tried to do it via "notification", but the same result, app crashes.

Any idea how can I implement vibrate on it?

Thanks!!

P.S.: I have android.permission.VIBRATE, so is not the problem. In fact I got virbation working on menu.

Upvotes: 1

Views: 3067

Answers (1)

Chris
Chris

Reputation: 326

I declare a public vibrator object in the activity that calls the game object. In my case the onCreate activity launches a MainGamePanel that extends a surfaceView. So in the onCreate activity I declare the vibrator object and initialize it with

public static Vibrator v;

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

//Then when I want to game to vibrate, inside of MainGamePanel I call

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

DroidzActivity.v.vibrate(pattern, 0);

Hope this helps!

Upvotes: 1

Related Questions