Garegin
Garegin

Reputation: 61

Vibrate android phone from non-activity class

I am trying to make my android phone vibrate after the ball hits the target in the game, so I created inner class Vibrate which extend Activity as my outer class is non-activity

public class TheGame extends GameThread {
  public class Vibrate extends Activity {
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  }
//some methods 

  protected void updateGame(float secondsElapsed){
    //updating coordinates and if ball hits the target >> vibrate 
    TheGame.Vibrate vib = new TheGame.Vibrate();
    vib.v.vibrate(500);

  }
 }

How can I call a vibration (Vibration v -inner class) from an outer class?? At this moment program stops at shows "unfortunately, app has stopped" and "too much output to process android" in Logcat //////////

Finally worked by the help of dhke. I just needed to access getSystemService(...) from Context which I Extended in outer class.

Upvotes: 0

Views: 947

Answers (1)

Hiren Patel
Hiren Patel

Reputation: 52800

Call static method in Non Activity class:

public class MyNonActivity{
    public static void vibrateDevice(Context mContext){
       Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
       // Vibrate for 500 milliseconds
       v.vibrate(500);
    }
}

Add permission in Manifest file.

<uses-permission android:name="android.permission.VIBRATE"/>

How to call from Activity:

MyNonActivity.vibrateDevice(getApplicationContext());

Done

Upvotes: 1

Related Questions