Pergunta

I am trying to use vibration in my android app, but it shows an error that The method getSystemservices(String) undefined for the type.

Here is the code i am used

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

how can i solve these error please help me. thanks

Foi útil?

Solução

public class MyClass {

private void Context mContext;

public MyClass(Context context){
    mContext = context;
}

public void someFunction(){
    // code
    Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    // .. code
}

}

Outras dicas

Try:

Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);

Don't forget to include permission in AndroidManifest.xml file:

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

Add this permission in your Manifest file:

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

Probably the class which you are calling that isn't an Activity or some other class which has it's own context. So if you are calling that in function you should do something like this :

public void someFunction(Context context){
   // .. code
   Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
   // .. more code
}

or in class

public class MyClass {

    private Context mContext;

    public MyClass(Context context){
        mContext = context;
    }

    public void someFunction(){
        // code
        Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        // .. code
    }
}

and as the other answers mentioned, don't forget to add permission to your manifest file :

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

Hope this helps! : )

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top