Android 摇一摇功能实现

现在有不少的应用开始实现了摇一摇功能,今天就把摇一摇的实现过程做一下记录。

用到知识点

1.加速度传感器
2.补间动画
3.手机震动 (Vibrator)
4.较短 声音/音效 的播放 (SoundPool)

首先布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/shake_bg"
    android:gravity="center"
    android:orientation="vertical" >

    <!-- 手掌展开后里面的图片 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="260dp"
        android:background="@color/shake_flower_bg"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/shake_flower"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:src="@drawable/shake_flower_img" />
    </LinearLayout>
    
    <LinearLayout
        android:id="@+id/shake_loading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/shakeImgDown"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ProgressBar
            android:layout_width="18dp"
            android:layout_height="18dp"
            android:indeterminateDuration="1100"
            android:indeterminateDrawable="@drawable/progressbar_shake_loading"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="正在搜寻美好"
                android:textSize="16dp"
                android:singleLine="true"
                android:ellipsize="end"
                android:layout_marginLeft="6dp"
                android:textColor="@color/white" />

    </LinearLayout>
    
    <!-- 摇一摇的结果 -->
    <RelativeLayout
        android:id="@+id/shake_result_layout"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_below="@+id/shakeImgDown"
        android:layout_marginLeft="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/shake_result_bg"
        android:gravity="center_vertical"
        android:visibility="visible"
        android:padding="@dimen/listitem_top" >

        <ImageView
            android:id="@+id/shake_result_img"
            android:layout_width="56dp"
            android:layout_height="56dp"
            android:layout_centerVertical="true"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/layout_padding"
            android:layout_toRightOf="@id/shake_result_img"
            android:gravity="center_vertical"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/shake_result_txt_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:gravity="center_vertical"
                android:textSize="16dp"
                android:textColor="@color/shake_reslut_txt_color" />

            <TextView
                android:id="@+id/shake_result_txt_value"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:gravity="center_vertical"
                android:textColor="@color/shake_reslut_txt_color"
                android:textSize="16dp" />

        </LinearLayout>
    </RelativeLayout>
    

    <!-- 手掌页面 -->
    <RelativeLayout
        android:id="@+id/shakeImgUp"
        android:layout_width="match_parent"
        android:layout_height="130dp"
        android:background="@color/shake_bg" >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/shake_logo_up" />

        <LinearLayout
            android:id="@+id/shakeImgUp_line"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_alignParentBottom="true"
            android:background="@color/black"
            android:visibility="gone" >

            <View
                android:layout_width="match_parent"
                android:layout_height="3dp"
                android:layout_gravity="bottom"
                android:background="@color/shake_line_bg" />
        </LinearLayout>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/shakeImgDown"
        android:layout_width="match_parent"
        android:layout_height="130dp"
        android:layout_below="@id/shakeImgUp"
        android:background="@color/shake_bg" >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/shake_logo_down" />

        <LinearLayout
            android:id="@+id/shakeImgDown_line"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_alignParentTop="true"
            android:background="@color/black"
            android:visibility="gone" >

            <View
                android:layout_width="match_parent"
                android:layout_height="3dp"
                android:layout_gravity="top"
                android:background="@color/shake_line_bg" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

布局写了好了就开始实现摇一摇功能了。

首先实现摇一摇的操作

public class ShakeListener implements SensorEventListener {
    // 速度阈值,当摇晃速度达到这值后产生作用
    private static final int SPEED_SHRESHOLD = 3000;
    // 两次检测的时间间隔
    private static final int UPTATE_INTERVAL_TIME = 70;
    // 传感器管理器
    private SensorManager sensorManager;
    // 传感器
    private Sensor sensor;
    // 重力感应监听器
    private OnShakeListenerCallBack onShakeListener;
    // 上下文
    private Context mContext;
    // 手机上一个位置时重力感应坐标
    private float lastX;
    private float lastY;
    private float lastZ;
    // 上次检测时间
    private long lastUpdateTime;

    // 构造器
    public ShakeListener(Context context) {
        // 获得监听对象
        mContext = context;
        start();
    }

    /**开始重力传感器的检测*/
    public void start() {
        // 获得传感器管理器
        sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            // 获得重力传感器
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        // 注册
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
    }

    /**停止检测*/ 
    public void stop() {
        sensorManager.unregisterListener(this);
    }

    /**重力感应器感应获得变化数据*/ 
    @Override
    public void onSensorChanged(SensorEvent event) {
        // 现在检测时间
        long currentUpdateTime = System.currentTimeMillis();
        // 两次检测的时间间隔
        long timeInterval = currentUpdateTime - lastUpdateTime;

        // 判断是否达到了检测时间间隔
        if (timeInterval < UPTATE_INTERVAL_TIME)
            return;
         // 现在的时间变成last时间
        lastUpdateTime = currentUpdateTime;

        // 获得x,y,z坐标
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        // 获得x,y,z的变化值
        float deltaX = x - lastX;
        float deltaY = y - lastY;
        float deltaZ = z - lastZ;

        // 将现在的坐标变成last坐标
        lastX = x;
        lastY = y;
        lastZ = z;

        double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000;
        // 达到速度阀值,发出提示
        if (speed >= SPEED_SHRESHOLD) {
            onShakeListener.onShake();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    /**摇晃监听接口*/ 
    public interface OnShakeListenerCallBack {
        public void onShake();
    }
    
    /**设置重力感应监听器*/ 
    public void setOnShakeListener(OnShakeListenerCallBack listener) {
        onShakeListener = listener;
    }
}

首先获取SensorManager,进而获取到加速度传感器,再设置监听器。然后在监听中根据传感器数值的变化,根据需要做响应的处理。当达到要求时进行回调,进而实现摇一摇后响应的逻辑(音效、动画等)。

摇一摇完成后动画

       /** 摇一摇手掌上部分动画 */
    public AnimationSet getUpAnim(){
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-0.8f);
        translateAnimation0.setDuration(OPEN_TIME);
        translateAnimation0.setAnimationListener(openAnimationListner);//图片上移动画监听
        TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0.8f);
        translateAnimation1.setDuration(CLOSE_TIME);
        translateAnimation1.setAnimationListener(closeAnimationListener);//图片下移动画监听
        translateAnimation1.setStartOffset(OFFSET_TIME);
        translateAnimation1.setInterpolator(new AccelerateInterpolator(1));
        animationSet.addAnimation(translateAnimation0);
        animationSet.addAnimation(translateAnimation1);
        return animationSet;
    }
    /** 摇一摇手掌下部分动画 */
    public AnimationSet getDownAnim(){
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0.8f);
        translateAnimation0.setDuration(OPEN_TIME);
        translateAnimation0.setAnimationListener(openAnimationListner);//图片上移动画监听
        TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-0.8f);
        translateAnimation1.setDuration(CLOSE_TIME);
        translateAnimation1.setAnimationListener(closeAnimationListener);//图片下移动画监听
        translateAnimation1.setStartOffset(OFFSET_TIME);
        translateAnimation1.setInterpolator(new AccelerateInterpolator(1));
        animationSet.addAnimation(translateAnimation0);
        animationSet.addAnimation(translateAnimation1);
        return animationSet;
    }

    /** 显示摇出结果动画 */
    public Animation getReusltAnim(){

        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-1,Animation.RELATIVE_TO_SELF,0);
        translateAnimation.setDuration(OPEN_TIME);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (mDoAnimationListener != null) {
                    mDoAnimationListener.onAnimEnd(SHAKE_RESULT_VISIBLE_CODE );
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        return translateAnimation;
    }
    /** 隐藏摇出结果动画 */
    public Animation getReusltGoneAnim(){
        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,3);
        translateAnimation.setDuration(OPEN_TIME);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (mDoAnimationListener != null) {
                    mDoAnimationListener.onAnimEnd(SHAKE_RESULT_GONE_CODE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        return translateAnimation;
    }
    /**手掌图开启动画监听*/
    public Animation.AnimationListener openAnimationListner = new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            //动画开始执行时回调
            if (mDoAnimationListener != null) {
                mDoAnimationListener.onAnimStart(OPEN_ANIM_CODE);
            }
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };

    /**手掌图合上动画监听*/
    public Animation.AnimationListener closeAnimationListener = new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //动画结束时回调
            if (mDoAnimationListener != null) {
                mDoAnimationListener.onAnimEnd(COLSE_ANIM_CODE);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };
    public interface DoAnimationListener{
        void onAnimStart(int code);
        void onAnimEnd(int code);
    }

震动

震动首先要加权限
<uses-permission android:name="android.permission.VIBRATE"/>
震动代码
 Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
 vibrator.vibrate(500);

接下来就是播放音效了

public class Sound {
    private static Sound mInstance;
    private SoundPool mSoundPool;//音效池
    private HashMap<Integer,Integer> mSoundPoolMap;//定义一个HashMap用于存放音频流的ID
    public static Sound getInstance() {
        if (mInstance == null) {
            mInstance = new Sound();
        }
        return mInstance;
    }

    /**初始化音效池---向音效池添加音效*/
    public void initPool(final Context context){
        mSoundPoolMap = new HashMap<>();
        mSoundPool = new SoundPool(3, AudioManager.STREAM_ALARM,1);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = null;
            audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();

            mSoundPool = new SoundPool.Builder()
                    .setMaxStreams(3)
                    .setAudioAttributes(audioAttributes)
                    .build();
        } else { // 5.0 以前
            mSoundPool = new SoundPool(3, AudioManager.STREAM_ALARM, 0);  // 创建SoundPool
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                mSoundPoolMap.put(0,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_sound_male),1));
                mSoundPoolMap.put(1,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_match),1));
                mSoundPoolMap.put(2,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_nomatch),1));
            }
        }).start();

    }
    /** 播放摇一摇开始声音 */
    public void playStartSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(0),1,1,0,0,1.3f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 播放摇一摇结束声音 */
    public void playEndSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(1),1,1,0,0,1.0f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 什么都没摇到 */
    public void playNotingSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(2),1,1,0,0,1.0f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

首先定义一个音效池,一个HashMap存放音效id,然后向音效池中添加音效,在合适的时机播放对应的音效。

以上几个步骤实现整个摇一摇效果

最终代码

动画部分
public class ShakeAnimation{
    /**展开动画*/
    public static final long OPEN_TIME = 500;
    /**关合动画*/
    public static final long CLOSE_TIME = 280;
    /**开合动画间隔*/
    public static final long OFFSET_TIME = 800;
    /**模拟延迟*/
    public static final long SIMULLATE_DELAY = 400;

    public static final int OPEN_ANIM_CODE = 1;
    public static final int COLSE_ANIM_CODE = 2;
    public static final int SHAKE_RESULT_GONE_CODE = 3;
    public static final int SHAKE_RESULT_VISIBLE_CODE = 4;
    private static DoAnimationListener mDoAnimationListener;
    private static ShakeAnimation needForAnim;
    public static ShakeAnimation getInstance(DoAnimationListener doAnimationListener) {
        mDoAnimationListener = doAnimationListener;
        if (needForAnim == null) {
            needForAnim = new ShakeAnimation();
        }
        return needForAnim;
    }
    /** 摇一摇手掌上部分动画 */
    public AnimationSet getUpAnim(){
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-0.8f);
        translateAnimation0.setDuration(OPEN_TIME);
        translateAnimation0.setAnimationListener(openAnimationListner);//图片上移动画监听
        TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0.8f);
        translateAnimation1.setDuration(CLOSE_TIME);
        translateAnimation1.setAnimationListener(closeAnimationListener);//图片下移动画监听
        translateAnimation1.setStartOffset(OFFSET_TIME);
        translateAnimation1.setInterpolator(new AccelerateInterpolator(1));
        animationSet.addAnimation(translateAnimation0);
        animationSet.addAnimation(translateAnimation1);
        return animationSet;
    }
    /** 摇一摇手掌下部分动画 */
    public AnimationSet getDownAnim(){
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation0 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0.8f);
        translateAnimation0.setDuration(OPEN_TIME);
        translateAnimation0.setAnimationListener(openAnimationListner);//图片上移动画监听
        TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-0.8f);
        translateAnimation1.setDuration(CLOSE_TIME);
        translateAnimation1.setAnimationListener(closeAnimationListener);//图片下移动画监听
        translateAnimation1.setStartOffset(OFFSET_TIME);
        translateAnimation1.setInterpolator(new AccelerateInterpolator(1));
        animationSet.addAnimation(translateAnimation0);
        animationSet.addAnimation(translateAnimation1);
        return animationSet;
    }

    /** 显示摇出结果动画 */
    public Animation getReusltAnim(){

        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,-1,Animation.RELATIVE_TO_SELF,0);
        translateAnimation.setDuration(OPEN_TIME);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (mDoAnimationListener != null) {
                    mDoAnimationListener.onAnimEnd(SHAKE_RESULT_VISIBLE_CODE );
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        return translateAnimation;
    }
    /** 隐藏摇出结果动画 */
    public Animation getReusltGoneAnim(){
        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,3);
        translateAnimation.setDuration(OPEN_TIME);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (mDoAnimationListener != null) {
                    mDoAnimationListener.onAnimEnd(SHAKE_RESULT_GONE_CODE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        return translateAnimation;
    }
    /**手掌图开启动画监听*/
    public Animation.AnimationListener openAnimationListner = new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            //动画开始执行时回调
            if (mDoAnimationListener != null) {
                mDoAnimationListener.onAnimStart(OPEN_ANIM_CODE);
            }
        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };

    /**手掌图合上动画监听*/
    public Animation.AnimationListener closeAnimationListener = new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //动画结束时回调
            if (mDoAnimationListener != null) {
                mDoAnimationListener.onAnimEnd(COLSE_ANIM_CODE);
            }
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };
    public interface DoAnimationListener{
        void onAnimStart(int code);
        void onAnimEnd(int code);
    }
}
音效部分
public class Sound {
    private static Sound mInstance;
    private SoundPool mSoundPool;//音效池
    private HashMap<Integer,Integer> mSoundPoolMap;//定义一个HashMap用于存放音频流的ID
    public static Sound getInstance() {
        if (mInstance == null) {
            mInstance = new Sound();
        }
        return mInstance;
    }

    /**初始化音效池---向音效池添加音效*/
    public void initPool(final Context context){
        mSoundPoolMap = new HashMap<>();
        mSoundPool = new SoundPool(3, AudioManager.STREAM_ALARM,1);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = null;
            audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();

            mSoundPool = new SoundPool.Builder()
                    .setMaxStreams(3)
                    .setAudioAttributes(audioAttributes)
                    .build();
        } else { // 5.0 以前
            mSoundPool = new SoundPool(3, AudioManager.STREAM_ALARM, 0);  // 创建SoundPool
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                mSoundPoolMap.put(0,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_sound_male),1));
                mSoundPoolMap.put(1,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_match),1));
                mSoundPoolMap.put(2,mSoundPool.load(context.getResources().openRawResourceFd(R.raw.shake_nomatch),1));
            }
        }).start();

    }
    /** 播放摇一摇开始声音 */
    public void playStartSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(0),1,1,0,0,1.3f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 播放摇一摇结束声音 */
    public void playEndSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(1),1,1,0,0,1.0f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 什么都没摇到 */
    public void playNotingSound(){
        try {
            mSoundPool.play(mSoundPoolMap.get(2),1,1,0,0,1.0f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
重力传感器部分
public class ShakeListener implements SensorEventListener {
    // 速度阈值,当摇晃速度达到这值后产生作用
    private static final int SPEED_SHRESHOLD = 3000;
    // 两次检测的时间间隔
    private static final int UPTATE_INTERVAL_TIME = 70;
    // 传感器管理器
    private SensorManager sensorManager;
    // 传感器
    private Sensor sensor;
    // 重力感应监听器
    private OnShakeListenerCallBack onShakeListener;
    // 上下文
    private Context mContext;
    // 手机上一个位置时重力感应坐标
    private float lastX;
    private float lastY;
    private float lastZ;
    // 上次检测时间
    private long lastUpdateTime;

    // 构造器
    public ShakeListener(Context context) {
        // 获得监听对象
        mContext = context;
        start();
    }

    /**开始重力传感器的检测*/
    public void start() {
        // 获得传感器管理器
        sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            // 获得重力传感器
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        // 注册
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
    }

    /**停止检测*/ 
    public void stop() {
        sensorManager.unregisterListener(this);
    }

    /**重力感应器感应获得变化数据*/ 
    @Override
    public void onSensorChanged(SensorEvent event) {
        // 现在检测时间
        long currentUpdateTime = System.currentTimeMillis();
        // 两次检测的时间间隔
        long timeInterval = currentUpdateTime - lastUpdateTime;

        // 判断是否达到了检测时间间隔
        if (timeInterval < UPTATE_INTERVAL_TIME)
            return;
         // 现在的时间变成last时间
        lastUpdateTime = currentUpdateTime;

        // 获得x,y,z坐标
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];

        // 获得x,y,z的变化值
        float deltaX = x - lastX;
        float deltaY = y - lastY;
        float deltaZ = z - lastZ;

        // 将现在的坐标变成last坐标
        lastX = x;
        lastY = y;
        lastZ = z;

        double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000;
        // 达到速度阀值,发出提示
        if (speed >= SPEED_SHRESHOLD) {
//          ToastUtils.showToast(mContext,"速度"+speed);
            onShakeListener.onShake();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    /**摇晃监听接口*/ 
    public interface OnShakeListenerCallBack {
        public void onShake();
    }
    
    /**设置重力感应监听器*/ 
    public void setOnShakeListener(OnShakeListenerCallBack listener) {
        onShakeListener = listener;
    }

}
Activity部分
public class BActivity extends AppCompatActivity implements ShakeAnimation.DoAnimationListener {

    @BindView(R.id.shake_flower)
    ImageView mShakeFlower;
    @BindView(R.id.shake_loading)
    LinearLayout mShakeLoading;
    @BindView(R.id.shake_result_img)
    ImageView mShakeResultImg;
    @BindView(R.id.shake_result_txt_name)
    TextView mShakeResultTxtName;
    @BindView(R.id.shake_result_txt_value)
    TextView mShakeResultTxtValue;
    @BindView(R.id.shake_result_layout)
    RelativeLayout mShakeResultLayout;
    @BindView(R.id.shakeImgUp_line)
    LinearLayout mShakeImgUpLine;
    @BindView(R.id.shakeImgUp)
    RelativeLayout mShakeImgUp;
    @BindView(R.id.shakeImgDown_line)
    LinearLayout mShakeImgDownLine;
    @BindView(R.id.shakeImgDown)
    RelativeLayout mShakeImgDown;
    private ShakeListener mShakeListener;
    private ShakeAnimation mShakeAnimation;
    private boolean hasReslut = false;
    private int shakeNum = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shake_root);
        ButterKnife.bind(this);
        setResultVisible(false);//初始时不显示结果
        showShakeLoading(false);//初始时不显示加载
        initShake();
    }

    private void initShake() {
        Sound.getInstance().initPool(this);
        mShakeListener = new ShakeListener(this);
        mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListenerCallBack() {
            @Override
            public void onShake() {
                startShake();//开始执行动画
                mShakeListener.stop();//取消摇动监听,动画结束之前不再监听
                vibrate(500);
                Sound.getInstance().playStartSound();
            }
        });
    }

    /**
     * 执行动画
     */
    private void startShake() {
        mShakeAnimation = ShakeAnimation.getInstance(this);
        mShakeImgDown.startAnimation(mShakeAnimation.getDownAnim());
        mShakeImgUp.startAnimation(mShakeAnimation.getUpAnim());
        if (mShakeResultLayout != null && mShakeResultLayout.getVisibility() == View.VISIBLE) {
            showResultGoneAnim();
        }
    }


    /**
     * 摇出的结果显示控制
     */
    private void setResultVisible(boolean isVisible) {
        if (mShakeResultLayout == null) {
            return;
        }
        if (isVisible) {
            mShakeResultLayout.setVisibility(View.VISIBLE);
        } else {
            mShakeResultLayout.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 正在加载
     */
    private void showShakeLoading(boolean isShow) {
        if (mShakeLoading == null) {
            return;
        }
        if (isShow) {
            mShakeLoading.setVisibility(View.VISIBLE);
        } else {
            mShakeLoading.setVisibility(View.GONE);
        }

    }


    private void setResultView(){
        showResultAnim();
        if(!hasReslut){
            mShakeResultImg.setImageResource(R.drawable.icon_sad_black);
            mShakeResultTxtName.setText("什么都没摇到");
            mShakeResultTxtValue.setVisibility(View.GONE);
        }else {
            mShakeResultImg.setImageResource(R.drawable.a);
            mShakeResultTxtName.setText("浑水摸鱼");

            mShakeResultTxtValue.setVisibility(View.VISIBLE);
            mShakeResultTxtValue.setText("距离10公里");
        }
        playResultSound();
    }
    private void playResultSound(){
        if(hasReslut){
            Sound.getInstance().playEndSound();
        }else {
            Sound.getInstance().playNotingSound();
        }
        shakeNum++;
        if(shakeNum%6==0){
            hasReslut = !hasReslut;
        }

    }

    /**
     * 动画开启
     */
    @Override
    public void onAnimStart(int code) {
        switch (code) {
            case ShakeAnimation.OPEN_ANIM_CODE:
                setHandLineVisible(true);
                break;

        }
    }

    /**
     * 动画结束
     */
    @Override
    public void onAnimEnd(int code) {
        switch (code) {
            case ShakeAnimation.COLSE_ANIM_CODE:
                setHandLineVisible(false);//
                setResultView();
                //showResultAnim();//显示结果
                setResultVisible(true);
                break;
            case ShakeAnimation.SHAKE_RESULT_GONE_CODE:
                setResultVisible(false);
                break;
            case ShakeAnimation.SHAKE_RESULT_VISIBLE_CODE:
                mShakeListener.start();//动画结束了,重新开始监听摇动
                break;
        }
    }

    /**
     * 手掌边线显示控制
     */
    private void setHandLineVisible(boolean isVisible) {
        if (mShakeImgUpLine != null) {
            if (isVisible) {
                mShakeImgUpLine.setVisibility(View.VISIBLE);

            } else {
                mShakeImgUpLine.setVisibility(View.GONE);
            }
        }
        if (mShakeImgDownLine != null) {
            if (isVisible) {
                mShakeImgDownLine.setVisibility(View.VISIBLE);

            } else {
                mShakeImgDownLine.setVisibility(View.GONE);
            }
        }
    }
    /**显示结果动画*/
    private void showResultAnim() {
        if (mShakeAnimation != null) {
            mShakeResultLayout.setAnimation(mShakeAnimation.getReusltAnim());
        }
    }
    /**显示结果隐藏的动画*/
    private void showResultGoneAnim(){
        if (mShakeAnimation != null) {
            mShakeResultLayout.setAnimation(mShakeAnimation.getReusltGoneAnim());
        }
    }
    /**震动*/
    private void vibrate(long milliseconds){
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }
    @Override
    public void onResume() {
        super.onResume();
        mShakeListener.start();
    }

    @Override
    public void onPause() {
        mShakeListener.stop();
        super.onPause();
    }

    @Override
    public void onStop() {
        mShakeListener.stop();
        super.onStop();
    }

}

代码就写到这块了,基本实现了仿微信摇一摇功能。
参考:https://www.cnblogs.com/wangyuehome/p/4608128.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,980评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,422评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,130评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,553评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,408评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,326评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,720评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,373评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,678评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,722评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,486评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,335评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,738评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,283评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,692评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,893评论 2 335