需要用到的:
1.SoundPool 声音池
2.Vibrator 振动器
3.Sensor 传感器
可写可不写:
//获取窗体
Window window = getWindow();
// //获取窗体下的DecorView(管理)
// View decorView = window.getDecorView();
// //设置窗体的位置()
// decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN );
//判断版本是否大于21
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//设置状态栏的颜色
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getRandomColor());
}
private ImageView shakeUpImg;
private ImageView shakeDownImg;
private int loadId;
private SoundPool soundPool;
private Vibrator vibrator;
private SensorManager systemService;
private Sensor defaultSensor;
private TranslateAnimation translateAnimation,translateAnimation1;
private ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activit_wx_layout);
init();
}
private void init() {
//图片
shakeUpImg = findViewById(R.id.shakeUpImg);
shakeDownImg = findViewById(R.id.shakeDownImg);
//获取传感器的管理类
systemService = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//加速度传感器.
defaultSensor = systemService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//初始化振动器.
initVibrator();
//初始化音乐.
initMusic();
//初始化动画.
initAnimation();
}
private void initAnimation() {
//补间动画
//一个往上移动up
translateAnimation = new TranslateAnimation(0, 0, 0, -200);
translateAnimation.setDuration(2000);//2秒钟
//一个往下移动down
translateAnimation1 = new TranslateAnimation(0, 0, 0, 200);
translateAnimation1.setDuration(2000);
}
private void initMusic() {
//加载音乐
soundPool=new SoundPool(1,1,1);
loadId = soundPool.load(this, R.raw.wx, 1);
soundPool.play(loadId, 1, 1, 0, 0, 1);
}
private void initVibrator() {
//和硬件的摇动进行配合震动的.
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
//第三个参数是事件上报的rate。
systemService.registerListener(this, defaultSensor, 300);
}
@Override
public void onSensorChanged(SensorEvent event) {
float xOffset = event.values[0];//获取x轴摇动的偏移量
float yOffset = event.values[1];//获取y轴摇动的偏移量
float zOffset = event.values[2];//获取z轴摇动的偏移量
//如果摇动的在X轴Y轴Z轴摇动的偏差大于15时,触发摇一摇事件.
if (Math.abs(xOffset) > 15 || Math.abs(yOffset) > 15 || Math.abs(zOffset) > 15) {
/**
* 300 触发事件后,300毫秒后开始震动.
* 500 震动时间为500毫秒。
*/
long[] pattern = {300, 500};
//开始震动.要添加权限在清单文件中.
vibrator.vibrate(pattern, -1);
//播放音乐
soundPool.play(loadId, 1.0f, 1.0f, 1, 1, 1.0f);
//播放动画
shakeUpImg.startAnimation(translateAnimation);
shakeDownImg.startAnimation(translateAnimation1);
}
}