image
前言
Android 開啟振動主要運(yùn)用了 Vibrator(振動器)祝沸,系統(tǒng)中有一個 Vibrator 抽象類珊膜,我們可以通過獲取 Vibrator實例調(diào)用里面的方法來完成振動功能湃番。
Vibrator vibrator = (Vibrator) getSystemServic(Service.VIBRATOR_SERVICE);
記得加權(quán)限:
<uses-permission android:name="android.permission.VIBRATE"/>
方法和參數(shù)
vibrator.vibrate(1000); //設(shè)置手機(jī)振動
vibrator.hasVibrator(); //判斷手機(jī)硬件是否有振動器
vibrator.cancel();//關(guān)閉振動
這里主要講解一下 vibrator.vibrate()斧抱,如下圖所示:
vibrate ( long milliseconds )
vibrator.vibrate(1000); //立刻振動,持續(xù)時間為1s
vibrate ( long milliseconds, AudioAttributes attributes )
API 文檔中對第二個參數(shù)的解釋是:
attributes: AudioAttributes corresponding to the vibration. For example,specify
USAGE_ALARM for alarm vibrations or USAGE_NOTIFICATION_RINGTONE for vibrations
associated with incoming calls.
意思就是說我們可以指定振動對應(yīng)的屬性
指定 USAGE_NOTIFICATION_RINGTONE 則是來電鈴聲振動
USAGE_ALARM 鬧鐘振動
使用
//API 21加入的
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
vibrator.vibrate(1000, audioAttributes);
vibrate ( long [ ] pattern , int repeat )
pattern long 類型數(shù)組
API 解釋:an array of longs of times for which to turn
the vibrator on or off匙姜;
官方文檔對pattern中元素的詳細(xì)說明:
Pass in an array of ints that are the durations for which to turn on or off
the vibrator in milliseconds.The first value indicates the number of milliseconds
to wait before turning the vibrator on. The next value indicates the number of
milliseconds for which to keep the vibrator on before turning it off.Subsequent
values alternate between durations in milliseconds to turn the vibrator off or to
turn the vibrator on.
大致意思:數(shù)組中的整數(shù)用來打開或關(guān)閉振動器,第一個值表示在打開振動器之前要等待的毫秒數(shù)下一個值
表示在關(guān)閉振動器之前保持振動器的毫秒數(shù)番宁,隨后的值交替執(zhí)行元莫。
repeat 振動重復(fù)的模式: -1 為不重復(fù)
0 為一直重復(fù)振動
1 則是指從數(shù)組中下標(biāo)為1的地方開始重復(fù)振動(不是振動一次!5骸u獯馈)
2 從數(shù)組中下標(biāo)為2的地方開始重復(fù)振動。
.....
//下面的 pattern[] 我們可以理解為 開啟振動后:
「等待0.1s」>「振動」>「振動2s」>「等待1s」>「振動1s」>「等待3s」
long pattern[] = {100, 2000, 1000, 1000,3000};
vibrator.vibrate(pattern,-1);
對于上面 repeat 和 pattern 的關(guān)系的還是依照上圖來說吧棋电,
圖片剛好和 long pattern[] = {100, 2000, 1000, 1000,3000}數(shù)組對應(yīng)(為了方便解釋
我將等待振動時間和振動時間當(dāng)做一組)
當(dāng) repeat 為 0 的時候會一直振動 此時會一直走 (0,1)茎截,(2,3)
下標(biāo) 4 剛好是等待時間 依然會執(zhí)行 然后本次重復(fù)結(jié)束,開啟下一次重復(fù)赶盔。
當(dāng) repeat 為 1 的時候 第一次振動會(0,1)企锌,(2,3),然后等待 3s招刨,本次振動結(jié)束,然后從下標(biāo)為 1
的地方開始重復(fù)振動哀军, 此時會走(1,2)沉眶,(3,4),(1,2)杉适,(3,4)谎倔;
當(dāng) repeat 為 2 的時候 第一次振動會(0,1),(2,3)猿推,然后等待 3s片习,本次振動結(jié)束,從下標(biāo)為2的
地方開始重復(fù)振動蹬叭,此時為(2,3)藕咏,然后等待3s,結(jié)束本次重復(fù)秽五,開啟下次(2,3)....
總結(jié):pattern [ ] 數(shù)組中第一位為振動等待時間孽查,重復(fù)執(zhí)行時指定的下標(biāo)為重復(fù)振動的第一位,亦為等待時間坦喘。
數(shù)組中個數(shù)為奇數(shù)時盲再,最后一位為等待時間,依舊會執(zhí)行瓣铣。
?
vibrate ( long[ ] pattern, int repeat, AudioAttributes attributes )
這個就不做過多解釋答朋,上面都有涉及到。
結(jié)束
本篇文章主要介紹了一下振動器常見 API 和使用棠笑,比較簡單梦碗。但都是親自測試所得。