无法找到一种振动手机的简单方法(源代码android)

时间:2017-12-07 13:26:21

标签: android

Context mcontext;
this.Context= mcontext;
//private Context context;
//this.context=context;
//super(mcontext);
Vibrator mVibrator = (Vibrator) mcontext.getSystemService(Context.VIBRATOR_SERVICE);
mVibrator.vibrate(300)

我在网上搜索了很多简单的代码来发出哔哔声,我发现了一个。但是我无法添加和编译几行代码来使手机振动。我遇到的所有线程都使用getsystemservice()。 Link to some code to vibrate on stackoverflow

单独的第一个getsystemservice()函数不起作用,我读到的某个地方需要由context object调用。我创建了一个上下文对象。然后它说上下文需要初始化。我尝试了this.context = context,这又出现了另一个错误。我正在进入这些编译错误的循环,这应该是一个简单的工作,只是振动手机。请告诉我这里我做错了什么。

这个问题不同,因为我从其他线程中获得了经验。正如其他线程给出的答案一样,只使用getsystemservice(),但这不起作用,因为它需要一个上下文。

更新:遇到此帖子How to pass context from MainActivity to another class in Android?

所以我做了这个

public class MyNonActivityClass{

// variable to hold context
private Context context;

//save the context received via constructor in a local variable

public MyNonActivityClass(Context context){
this.context=context;
}

}

但是我得到错误mcallback可能没有在这里初始化。

private final Callback mCallback;

然后我在哪里添加

MyNonActivityClass mClass = new MyNonActivityClass(this);

1 个答案:

答案 0 :(得分:1)

您从哪里拨打Vibrator service

如果它来自活动,那么

Vibrator mVibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)

或者如果它来自Frgament,那么

 Vibrator mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)

或在您的代码中更新此内容,例如

void vibrate(Context mcontext ){
    Vibrator mVibrator = (Vibrator) 
    mcontext.getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(300)
}