设置手机震动,首先要在配置文件中添加权限:
<uses-permission android:name="android.permission.VIBRATE"/>
其次取得Vibrator对象。
vibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
代码很简单,相关讲解看代码注释就成。
package com.kevin.vibrator;
import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Main extends Activity {
private Vibrator vibrator;
private ToggleButton tb_short,tb_long,tb_tune;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 取得Vibrator对象
vibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
tb_short = (ToggleButton) findViewById(R.id.tb_short);
tb_long = (ToggleButton) findViewById(R.id.tb_long);
tb_tune = (ToggleButton) findViewById(R.id.tb_tune);
tb_short.setOnClickListener(new ToggleButtonOnClickListener());
tb_long.setOnClickListener(new ToggleButtonOnClickListener());
tb_tune.setOnClickListener(new ToggleButtonOnClickListener());
}
class ToggleButtonOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
ToggleButton tb = (ToggleButton)v;
switch (tb.getId()) {
case R.id.tb_short:
{
if (tb.isChecked()) {
// 设置震动周期
/*
* 第一个参数是个长整型的时间数组,数组中第一个值表示在vibrator
* 打开前等待的毫秒数,接下来的值表示vibrator关闭前等待的毫秒数,
* 以此类推。
* 第二个参数是设置震动的模式,-1的话,只震动一轮,0的话震动一直持续
*/
vibrator.vibrate(new long[]{100,10,100,1000}, -1);
Toast.makeText(Main.this, getString(R.string.processing), Toast.LENGTH_SHORT).show();
}else{
// 取消震动
vibrator.cancel();
Toast.makeText(Main.this, getString(R.string.cancel), Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.tb_long:
{
if (tb.isChecked()) {
// 设置震动周期
vibrator.vibrate(new long[]{100,100,100,1000}, 0);
Toast.makeText(Main.this, getString(R.string.processing), Toast.LENGTH_SHORT).show();
}else{
// 取消震动
vibrator.cancel();
Toast.makeText(Main.this, getString(R.string.cancel), Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.tb_tune:
{
if (tb.isChecked()) {
// 设置震动周期
vibrator.vibrate(new long[]{1000,50,1000,50,1000}, 0);
Toast.makeText(Main.this, getString(R.string.processing), Toast.LENGTH_SHORT).show();
}else{
// 取消震动
vibrator.cancel();
Toast.makeText(Main.this, getString(R.string.cancel), Toast.LENGTH_SHORT).show();
}
}
break;
default:
break;
}
}
}
}