Reputation: 585
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);
}
}
Upvotes: 4
Views: 13700
Reputation: 586
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);
}
}
Upvotes: 5
Reputation: 8489
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.
Upvotes: 0
Reputation: 132982
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);
Upvotes: 3