繁体   English   中英

如何在不扩展活动的类中访问android中的振动器?

[英]How to access vibrator in android in a class that is not extending activity?

我正在尝试使用名为VibrationManager的类中的以下内容访问振动器,并且该类未扩展Activity

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

但是日食抛出和错误

对于类型VibrationManager,未定义方法getSystemService(String)

这是我全班

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){

}

}

请帮忙

您的课程没有方法getSystemService因为该课程没有扩展Activity

如果您不想使用getSystemService方法,则需要使用VibrationManager类来扩展活动,或者需要接收该活动的上下文。

只需将代码更改为使用上下文即可,为此,您还需要在静态调用中获取上下文。

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){

    }
}

如果在从不同的视图访问上下文时遇到问题,可以执行以下操作:

  • 创建一个扩展应用程序的类(例如MyApplication)

  • 在清单中将该类声明为Application类,如下所示:

      <application android:name="your.project.package.MyApplication" ... 
  • 默认情况下,应用程序类是单例,但是您需要创建一个getInstance方法,如下所示:

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

完成后,您可以从应用程序中的任何位置访问上下文,而无需传递如下所示的大量引用:

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

到那里,您不仅可以致电振动器服务,还可以致电所需的任何服务...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM