开发学院手机开发Android 开发 Android中实现振动效果 阅读


 2012-06-04 16:51:31 来源:WEB开发网   
核心提示:实现振动效果,需要调用Android系统提供的Vibrator,Android中实现振动效果,Vibrator主要的API有:Ÿ vibrate(long milliseconds)振动指定的时间,Ÿ vibrate(long[] pattern, int repeat)按照给定的模式振动,

Ÿ vibrate(long milliseconds)振动指定的时间。

Ÿ vibrate(long[] pattern, int repeat)按照给定的模式振动。



Ÿ cancel()取消振动。

下面是不同振动效果的例子(来自参考资料[2]),这些代码需要在一个Context(如Activity, Service)中进行调用。注意默认情况下当屏幕暗掉时,振动也会停止,可以通过设置屏幕常亮来使振动持续。

1.1 振动指定的时间
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 200 milliseconds


1.2 按照指定的模式进行振动

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


dash, short_gap, dash, short_gap, dash, // o


dot, short_gap, dot, short_gap, dot, // s



// 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


// 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!


Tags:Android 实现 振动

编辑录入:爽爽 [复制链接] [打 印]