Android中实现振动效果
2012-06-04 16:51:31 来源:WEB开发网实现振动效果,需要调用Android系统提供的Vibrator,Vibrator主要的API有:
Ÿ vibrate(long milliseconds)振动指定的时间。
Ÿ vibrate(long[] pattern, int repeat)按照给定的模式振动。
Patterns指定振动模式,数组的每个整数是一个时间间隔,第一个整数指定等待多长时间开始振动,后面的参数依次重复指定振动持续的时间和振动间隔的时间。
Repeat指定patter数组中的一个索引值,从这个值开始不断重复振动模式,如果为-1则不重复振动。
Ÿ cancel()取消振动。
下面是不同振动效果的例子(来自参考资料[2]),这些代码需要在一个Context(如Activity, Service)中进行调用。注意默认情况下当屏幕暗掉时,振动也会停止,可以通过设置屏幕常亮来使振动持续。
1.1 振动指定的时间
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 200 milliseconds
v.vibrate(300);
1.2 按照指定的模式进行振动
按照”S-O-S”求救信号模式进行振动:
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// This example will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
int dot = 200; // Length of a Morse Code "dot" in milliseconds
int dash = 500; // Length of a Morse Code "dash" in milliseconds
int short_gap = 200; // Length of Gap Between dots/dashes
int medium_gap = 500; // Length of Gap Between Letters
int long_gap = 1000; // Length of Gap Between Words
long[] pattern = {
0, // Start immediately
dot, short_gap, dot, short_gap, dot, // s
medium_gap,
dash, short_gap, dash, short_gap, dash, // o
medium_gap,
dot, short_gap, dot, short_gap, dot, // s
long_gap
};
// Only perform this pattern one time (-1 means "do not repeat")
v.vibrate(pattern, -1);
1.3 重复振动直到用户取消
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start immediately
// Vibrate for 200 milliseconds
// Sleep for 500 milliseconds
long[] pattern = { 0, 200, 500 };
// The "0" means to repeat the pattern starting at the beginning
// CUIDADO: If you start at the wrong index (e.g., 1) then your pattern will be off --
// You will vibrate for your pause times and pause for your vibrate times !
v.vibrate(pattern, 0);
In another part of your code, you can handle turning off the vibrator as shown below:
view source
print?
// Stop the Vibrator in the middle of whatever it is doing
// CUIDADO: Do *not* do this immediately after calling .vibrate().
// Otherwise, it may not have time to even begin vibrating!
v.cancel();
- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接