Android开发学习:[29]android手机震动代码
1、首先我们新建一个activity.将其设置为启动项,记得在清单文件中添加intent-filter:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/01bd69f7980e5f206283ba68bd20b93acc898e45.jpg)
2、然后我们在界面代码中添加三个按钮,分别是长、短、暂停震动的按钮
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.basillee.asus.demo.MainActivity10">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="shortButton"
android:id="@+id/short_vibrate"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="shortButton"
android:id="@+id/long_vibrate"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="shortButton"
android:id="@+id/stop_vibrate"/>
</LinearLayout>
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/dccb47de45078801158230f2b18ca608a40f8245.jpg)
3、然后我们为每个按钮添加点击事件监听
shortButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrator.vibrate(new long[]{100,100},0);
}
});
longButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrator.vibrate(new long[]{1000,3000,1000,3000},-1);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrator.cancel();
}
});
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/95bd4e8c9bcec7f8bc85b86e034ce54a2e27fb45.jpg)
4、完成以上步骤之后我们就可以点击android studio上面的运行按钮了
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/6a408cdd3340b6f3d075e6af12c0affce086ee45.jpg)
5、然后打开我们的模拟器
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/6061b9cd0c6efbf257419064127bbbf4db58da45.jpg)
6、最后运行此实例的界面如下,放入真实手机中测试便会震动。记得要添加权限啊
![Android开发学习:[29]android手机震动代码](https://exp-picture.cdn.bcebos.com/3fe32442a07aa010cdc1098bbfbb19efa35f3e4a.jpg)