android實現手機震動 1.在AndroidManifest.xml中添加震動權限 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://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>
2.實現震動
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 /* 如:只想震動一次,時間為200ms,可寫為 long [] pattern = {0,200}; // 停止 開啟 vibrator.vibrate(pattern,-1); //重復兩次上面的pattern 如果只想震動一次,index設-1 */ } public void onStop(){ super.onStop(); vibrator.cancel(); //停止震動 } } |