Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現調用手機震動的方法

編輯:關於 Android 程式設計

本文介紹如何在 Android 中調用系統震動功能,供大家參考。

調用 Android 系統震動只需要一個類——Vibrator,它位於 android.os 包中。由於屬於系統級服務,需要在 manifest.xml 中設置相應權限:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="uni.vibrator" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".VibratorDemoActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.VIBRATE" /> </manifest> 

一起來看下 SDK 文檔:Vibrator 類用於操作設備上的震動,如果你的線程退出了,那麼啟動的震動也會停止。

public void vibrate(long[] pattern, int repeat) —— 根據給定的節奏震動。傳入一個整型數組作為關閉和開啟震動的持續時間(毫秒):第一個值表示等待震動開啟的毫秒數,下一個值表示保持震動的毫秒數,後續值交替表示震動關閉與開啟的時長。若希望節奏重複,可傳入 repeat 參數表示從數組哪個索引開始重複,-1 表示不重複。

此外還有一個 cancel() 方法,用於取消震動。

演示代碼:

 /* * @author octobershiner * SE.HIT * 一個使用android手機震動的demo * */ package uni.vibrator; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Vibrator; public class VibratorDemoActivity extends Activity { private Vibrator vibrator; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /* * 想設置震動大小可以通過改變pattern來設定,如果開啟時間太短,震動效果可能感覺不到 * */ vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); long [] pattern = {100,400,100,400}; // 停止 開啟 停止 開啟 vibrator.vibrate(pattern,2); //重復兩次上面的pattern 如果只想震動一次,index設為-1 } public void onStop(){ super.onStop(); vibrator.cancel(); } }

以上就是調用 Android 系統震動的實現方法,希望對大家的開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved