Skip to content Skip to sidebar Skip to footer

How To Access Vibrator In Android In A Class That Is Not Extending Activity?

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.VIBRA

Solution 1:

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.

publicclassVibrationManager {

    privatestaticVibrationManager me;
    privateContext context;

    Vibrator v = null;

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

    publicstaticVibrationManagergetManager(Context context) {
        if(me == null){
            me = newVibrationManager();
        }
        me.setContext(context);
        return me;
    }

    privatevoidsetContext(Context context){
        this.context = context;
    }

    publicvoidvibrate(long[] pattern){

    }
}

Solution 2:

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:

    publicclassMyApplicationextendsApplication {
    
        privatestatic MyApplication instance;
    
        publicvoidonCreate() {
            instance = this;
        }
    
        publicstatic MyApplication getInstance() {
            return instance;
        }
    }
    

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

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

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

Post a Comment for "How To Access Vibrator In Android In A Class That Is Not Extending Activity?"