Android中实现振动效果 (How to Imeplement Vibration Effect In Andoid)

实现振动效果,需要调用Android系统提供的VibratorVibrator主要的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();

1.4     参考

[1] [Vibrator. http://developer.android.com/reference/android/os/Vibrator.html#vibrate(long[], int)

[2] Vibration Examples for Android Phone Development.

http://android.konreu.com/developer-how-to/vibration-examples-for-android-phone-development/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值