Android中用Vibrator类的对象来控制震动器。
要获得设备的震动器,要调用getSystemService(String)函数,以VIBRATOR_SERVICE 为参数。
Vibrator类有以下成员函数:
| Public Methods | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| abstract void | cancel() Turn the vibrator off. | ||||||||||
| abstract boolean | hasVibrator() Check whether the hardware has a vibrator. | ||||||||||
| abstract void | vibrate(long[] pattern, int repeat) Vibrate with a given pattern. | ||||||||||
| abstract void | vibrate(long milliseconds) Vibrate constantly for the specified period of time. | ||||||||||
如果只传递一个long参数,这个参数用来指定振动的毫秒数,如要震动5秒,则按如下方式调用:
vibrator.vibrate(5000);
如果传递多个参数,震动器就按照给定的模式震动,震动模式由数组pattern指定。如要按以下方式震动:
等待1秒,震动2秒,等待1秒,震动3秒,则把数组设置如下:
long[] pattern = {1000, 2000, 1000, 3000};
第二个参数为-1表示不重复, 如果不是-1, 比如改成1, 表示从前面这个long数组的下标为1的元素开始重复(这个说法应该靠谱,而不是重复的次数,因为当用这个数组的时候传4过去,会出现下图情况)

完整的代码如下:
package com.peng.hello.activity;
import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.TextView;
public class HelloActivity extends Activity
{
Vibrator vibrator;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
}
public void onMyClick(View view)
{
long[] pattern = {800, 50, 400, 30}; // OFF/ON/OFF/ON...
vibrator.vibrate(pattern, 4);
Toast.makeText(this, "button click", Toast.LENGTH_SHORT).show();
// vibrator.cancel();
}
}以上程序要添加一个按钮, onMyClick 为按钮的响应程序。在mail.xml中添加如下程序:<Button
android:id="@+id/Btm01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:onClick="onMyClick"></Button>记得在AndroidManifest.xml文件添加权限,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peng.hello.activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".HelloActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>注,以上程序红色部分为添加进去的。
还有程序要在真机上运行才能有震动的效果,模拟器上不支持震动的。
版权声明:本文为peng08303原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。