The article links: mp.weixin.qq.com/s/n6EXvfmpN…

Shake a red envelope effect has been a cliche, using the sensor of the phone to identify shake, at the same time in the process of animation + vibration + sound effect. Ps: Baidu web page version “shake a shake” three words, there will be an effect, a ha! Effect:

Shake mainly through the SensorManager to monitor the phone, SensorEventListener, onSensorChanged to judge, according to the acceleration to determine the degree of shake.

ShakeSensorListener shakeListener = new ShakeSensorListener(); SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); private class ShakeSensorListener implements SensorEventListener { @Override public void onSensorChanged(SensorEvent {// Avoid shaking all the timeif (isShake) {
            return; } // Start animation im.start();float[] values = event.values; /* * x: the acceleration of gravity in the x direction, positive * y: the acceleration of gravity in the y direction, positive * z: the acceleration of gravity in the Z direction, positive */float x = Math.abs(values[0]);
        float y = Math.abs(values[1]);
        floatz = Math.abs(values[2]); // The acceleration exceeds 19, and the roll succeedsif (x > 19 || y > 19 || z > 19) {
            isShake = true; // Play the sound playSound(mainactivity.this); // Note that permission vibrate(500); // We can request the server... new Handler().postDelayed(newRunnable() {
                @Override
                public void run() {// showDialog(); // Animation cancels im.cancel(); }}, 1000); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }Copy the code

If the phone is shaking all the time, onSensorChanged will be constantly called, and we only want the effect of shaking once, so we add isShake field to judge. After the shake event is complete, set false to continue the shake.

Register to listen, and don’t forget to unregister.

@Override
protected void onResume() {/ / registered to monitor the acceleration sensor sensorManager. RegisterListener (shakeListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST); super.onResume(); } @Override protected voidonPause() {/ / cancellation registration sensorManager unregisterListener (shakeListener); super.onPause(); }Copy the code

Shake the process to perform animation effects.

ObjectAnimator anim = ObjectAnimator.ofFloat(imgHand,"rotation",0f,45f,-30f,0f);
anim.setDuration(500);
anim.setRepeatCount(ValueAnimator.INFINITE);
Copy the code

Play the sound, which is placed in the RAW resource file.

private void playSound(Context context) {
    MediaPlayer player = MediaPlayer.create(context,R.raw.shake_sound);
    player.start();
}
Copy the code

Vibration effect, this note to add permissions in the AndroidManifest file < USES – permission android: name = “android. Permission. VIBRATE” / >

private void vibrate(long milliseconds) {
    Vibrator vibrator = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
    vibrator.vibrate(milliseconds);
}
Copy the code

Once you shake it, here you can shake it again after the frame disappears.

private void showDialog() {
    final AlertDialog mAlertDialog = new AlertDialog.Builder(this).show();
    View view = LayoutInflater.from(this).inflate(R.layout.layout_dialog,null);
    mAlertDialog.setContentView(view);
    mAlertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {@override public void onCancel(DialogInterface dialog) {// Here let the box cancel, can perform the next shake isShake =false; mAlertDialog.cancel(); }}); Window window = mAlertDialog.getWindow(); window.setBackgroundDrawable(new ColorDrawable(0x00000000)); }Copy the code

At this point, a set of shake a shake effect is complete!

Github address: github.com/taixiang/sh…

Welcome to my personal blog: www.manjiexiang.cn/

More wonderful welcome to pay attention to micro signal: spring breeze ten miles is better to know you to learn together, progress together, welcome to get on the car, have a problem at any time contact, solve together!!