首页 > 代码库 > Android 震动功能

Android 震动功能

主界面代码:

package com.example.vibrator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button btn_vibrator_0;
	private Button btn_vibrator_1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn_vibrator_0 = (Button) findViewById(R.id.btn_vibrator_0);
		btn_vibrator_1 = (Button) findViewById(R.id.btn_vibrator_1);
		/**
		 * 点击设置默认震动模式,震动100毫秒
		 * */
		btn_vibrator_0.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//停止震动
				VibratorUtil.VibrateCancel(MainActivity.this);
				VibratorUtil.Vibrate(MainActivity.this,100);   //震动100ms  
			}
		});
		/**
		 * 点击设置自定义震动模式,重复震动
		 * */
		btn_vibrator_1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				//停止震动
				VibratorUtil.VibrateCancel(MainActivity.this);
				//设置震动参数,停50毫秒,震动100毫秒
				long[] prams={50,100,50,100};
				VibratorUtil.Vibrate(MainActivity.this,prams,true);   //震动100ms  
			}
		});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//停止震动
		VibratorUtil.VibrateCancel(MainActivity.this);
	}
	
}
震动功能模块:

package com.example.vibrator;

import android.app.Activity;
import android.app.Service;
import android.os.Vibrator;

/**
 * 手机震动工具类
 * 
 * @author Administrator
 * 
 */
public class VibratorUtil {

	/**
	 * final Activity activity :调用该方法的Activity实例 
	 * long milliseconds :震动的时长,单位是毫秒
	 */
	public static void Vibrate(final Activity activity, long milliseconds) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(milliseconds);
	}

	/**
	 * final Activity activity :调用该方法的Activity实例 
	 * long[] pattern :自定义震动模式。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒
	 * boolean isRepeat :是否反复震动,如果是true,反复震动,如果是false,只震动一次
	 * */
	public static void Vibrate(final Activity activity, long[] pattern,
			boolean isRepeat) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(pattern, isRepeat ? 1 : -1);
	}
	/**
	 * 停止震动
	 * */
	public static void VibrateCancel(final Activity activity){
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.cancel();
	}
	

}


示例代码地址:http://download.csdn.net/detail/stop_pig/8213105

Android 震动功能