Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 震動功能

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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved