我希望我的应用程序振动3秒钟,但它不起作用,我无法弄清楚原因。当我点击按钮时,它什么也没做。起初我尝试在主要活动中进行,但结果相同。
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final Button vibrateButton = new Button(this);
final Intent vibration = new Intent(this, MyService.class);
vibrateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(vibration);
}
});
}
服务
public class MyService extends IntentService {
public MyService()
{
super("MyService");
}
@Override
protected void onHandleIntent(Intent vibration)
{
Vibrator vibe = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(3000);
}
}
答案 0 :(得分:2)
尝试:
import android.os.Vibrator;
...
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 3000 milliseconds
v.vibrate(3000);
注意:强>
不要忘记在AndroidManifest.xml文件中包含权限:
<uses-permission android:name="android.permission.VIBRATE"/>