Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error when use getSystemService

Tags:

android

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);
    }

}
like image 990
egydeveloper Avatar asked Feb 17 '23 03:02

egydeveloper


2 Answers

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);
    }

}
like image 180
luisurrutia Avatar answered Feb 26 '23 17:02

luisurrutia


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);
like image 20
ρяσѕρєя K Avatar answered Feb 26 '23 18:02

ρяσѕρєя K