Question

I'm trying to access the vibrator using the following in class called VibrationManager and the class is not extending Activity

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

but eclipse throws and error like

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

This is my whole Class

public class VibrationManager {

private static VibrationManager me = null;

Vibrator v = null;

private Vibrator getVibrator(){
    if(v == null){
        v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    }
    return v;
}

public static VibrationManager getManager() {
    if(me == null){
        me = new VibrationManager();
    }
    return me;
}

public void vibrate(long[] pattern){

}

}

Please help

Was it helpful?

Solution

Your class doesn't have the method getSystemService since this class dosen't extend a Activity.

If you wan't to use the getSystemService method you need your class VibrationManager to extend an activity or you need to receive a context for that.

Just change your code to use a context, for that you will need to also get a context in your static call.

public class VibrationManager {

    private static VibrationManager me;
    private Context context;

    Vibrator v = null;

    private Vibrator getVibrator(){
        if(v == null){
            v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        }
        return v;
    }

    public static VibrationManager getManager(Context context) {
        if(me == null){
            me = new VibrationManager();
        }
        me.setContext(context);
        return me;
    }

    private void setContext(Context context){
        this.context = context;
    }

    public void vibrate(long[] pattern){

    }
}

OTHER TIPS

If you have problems accessing the context from different Views you can do this:

  • Create a class that extends Application (e.g. MyApplication)

  • Declare that class in your manifest as your Application class as shown below:

     <application
       android:name="your.project.package.MyApplication"
       ...
    
  • Application class is by default a singleton, but you need to create a getInstance method as shown below:

    public class MyApplication extends Application {
    
        private static MyApplication instance;
    
        public void onCreate() {
            instance = this;
        }
    
        public static MyApplication getInstance() {
            return instance;
        }
    }
    

Done, you can access the context from anywhere in your app without passing so many references as follows:

MyApplication app = MyApplication.getInstance()
Vibrator v = (Vibrator) app.getSystemService(Context.VIBRATOR_SERVICE);

There you go, you can not only call vibrator service but any service you want...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top