Android系统中Vibrator对象负责对手机震动的处理,具体的实现方法:
1.获取振动器Vibrator的实例:
- Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
-
- getSystemService(VIBRATOR_SERVICE):获得一个震动的服务
2.调用vibrate方法来产生震动:
- 只向vibrate()传递一个参数,这个参数用来指定振动的毫秒数
-
- vibrator.vibrate(5000);
-
-
- long[] pattern = {1000, 2000, 1000, 3000};
-
- vibrator.vibrate(pattern, -1);
3.取消震动
- vibrator.cancel();
4.在AndroidManifest.xml文件添加权限
- <uses-permission android:name="android.permission.VIBRATE" />
下面的实例包含了产生震动的两个方法
VibratorDemoActivity.java
- package com.lingdududu.test;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Vibrator;
- import android.view.MotionEvent;
-
-
-
-
-
-
- public class VibratorDemoActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
-
- long[] pattern = {1000, 2000, 1000, 3000};
- vibrator.vibrate(pattern, -1);
-
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- if (event.getAction() == MotionEvent.ACTION_MOVE) {
- Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
- vibrator.vibrate(1000);
- }
- return super.onTouchEvent(event);
- }
- }
-
注:记得在AndroidManifest.xml文件添加权限,还有程序要在真机上运行才能有震动的效果,模拟器上不支持震动的。
PS:我正在参加IT博客大赛,欢迎大家来投我一票的
http://blog.51cto.com/contest2011/3061169
本文转自 lingdududu 51CTO博客,原文链接: http://blog.51cto.com/liangruijun/724042