實作振動效果,需要調用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();
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/