简体   繁体   English

如何在Android库模块中使用振动器

[英]How to use the Vibrator in an Android Library Module

My goal is to make a simple library with some basic vibration methods so that I can have a more diverse and native set of options in some other frameworks. 我的目标是使用一些基本的振动方法制作一个简单的库,以便在其他一些框架中可以有一组更多样化和更原生的选项。 My problem is that I cannot use getActivity() or getSystemService(Context.VIBRATOR_SERVER) inside the library. 我的问题是我无法在库中使用getActivity()getSystemService(Context.VIBRATOR_SERVER)

Here is the library class I have so far: 这是我到目前为止拥有的库类:

import android.os.Vibrator;
public class Vibration {

private Vibrator _vibrator;

     public static void Vibrate(long milliseconds ){
         Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
         //getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
         v.vibrate(VibrationEffect.createOneShot(
            milliseconds,VibrationEffect.DEFAULT_AMPLITUDE));
     }
}

I am getting Cannot resolve symbol 'Context' , and the same for getSystemService 我正在获取Cannot resolve symbol 'Context' ,对于getSystemService也是一样

Anyone have an idea of to call these methods from the library? 任何人都有从库中调用这些方法的想法吗?

you need to pass context object in Vibrate() method as below: 您需要在Vibrate()方法中传递上下文对象,如下所示:

public static void Vibrate(long milliseconds, Context context) {
    Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(VibrationEffect.createOneShot(
            milliseconds, VibrationEffect.DEFAULT_AMPLITUDE));
}

and for Context you need to import import android.content.Context; 对于Context,您需要导入import android.content.Context;

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

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