4

i had this error The method getSystemService(String) is undefined for the type WebAppInterface when I use " getSystemService". I worked in interface class not activity class .

 @JavascriptInterface
public void Viber(String value ) {
    if (value.equals("on")) {
        // Get instance of Vibrator from current Context
        Vibrator v = (Vibrator)getSystemService(mContext.VIBRATOR_SERVICE);

        // Vibrate for 300 milliseconds
        v.vibrate(300);
    }

}

4 Answers 4

5

It's cause the metod getSystemService belongs to the class Context, so you have to run it on a context but you're running it from an activity.

@JavascriptInterface
public void Viber(Context cn, String value) {
    if (value.equals("on")) {
        // Get instance of Vibrator from current Context
        Vibrator v = (Vibrator) cn.getSystemService(Context.VIBRATOR_SERVICE);

        // Vibrate for 300 milliseconds
        v.vibrate(300);
    }

}
0
3

for getting System Services from non Android application components you will need to pass Context to java class as:

@JavascriptInterface
public void Viber(String value, Context context) {
    if (value.equals("on")) {
        // Get instance of Vibrator from current Context
        Vibrator v = (Vibrator)context.getSystemService(mContext.VIBRATOR_SERVICE);

        // Vibrate for 300 milliseconds
        v.vibrate(300);
    }
}

Or you can use WebAppInterface class Contstorctor as:

public class WebAppInterface{
Context context;

 public WebAppInterface(Context context){
   this.context=context;
  }
 ....


}

now use context for calling getSystemService as from Viber method:

Vibrator v = (Vibrator)context.getSystemService(mContext.VIBRATOR_SERVICE);
0

Reference

The method getSystemService(String) is undefined for the type Listen

getSystemService is a method of the class Context, so you'll need to run it on a context.

The original code you copied it from was probably meant to be run from an Activity-derived class. You need to pass a Context argument into your method if it's not inside an Activity.

0

mContext.VIBRATOR_SERVICE => Context.VIBRATOR_SERVICE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.