android - 找不到一个简单的方法来振动手机(源代码android)

标签 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 might not have been initialized here.

private final Callback mCallback;

然后我在哪里添加这个

MyNonActivityClass mClass = new MyNonActivityClass(this);

最佳答案

从哪里调用 Vibrator 服务

如果它来自 Activity ,那么,

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

关于android - 找不到一个简单的方法来振动手机(源代码android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696184/

相关文章:

android - 使用 asynctask 延迟显示 UI

android - 在对话框中添加数字

android - getLine1Number() 不工作

java - 从 asset 文件夹中执行 cp 命令 android

c# - 使用 Unity3d 连接到 MySQL 服务器?

android - 为 Android 联系人照片大小声明常量?

android - 单击 ListView 中的图像按钮即可更改图像资源

android - 如何使用android中的服务每6秒获取一次位置更新

android - 如何将 Java.Util.Date 转换为 System.DateTime

android - android中RTC和RTC_WAKEUP的区别