Android的手机震动
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(); //停止震动 } } |