android實現微信搖一搖

出處:http://jingyan.baidu.com/article/f3ad7d0f13e07909c3345baa.html


android實現搖一搖功能簡單實現,動畫自定義

android實現微信搖一搖

工具/原料

  • android開發工具 有加重器功能的安卓手機

方法/步驟

  1. 配置文件

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:background="#111"

        android:orientation="vertical" >


        <ImageView

            android:id="@+id/shakeBg"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:contentDescription="@null"

            android:src="@drawable/shakehideimg_man" />


        <LinearLayout

            android:id="@+id/shake_content"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:gravity="center"

            android:orientation="vertical" >


            <RelativeLayout

                android:id="@+id/shakeImgUp"

                android:layout_width="fill_parent"

                android:layout_height="140dip"

                android:background="#111"

                android:visibility="visible" >


                <ImageView

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_alignParentBottom="true"

                    android:layout_centerHorizontal="true"

                    android:contentDescription="@null"

                    android:src="@drawable/shake_logo_up" />

            </RelativeLayout>


            <RelativeLayout

                android:id="@+id/shakeImgDown"

                android:layout_width="fill_parent"

                android:layout_height="140dip"

                android:background="#111"

                android:visibility="visible" >


                <ImageView

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_centerHorizontal="true"

                    android:contentDescription="@null"

                    android:src="@drawable/shake_logo_down" />

            </RelativeLayout>

        </LinearLayout>


    </RelativeLayout>

  2. 代碼編寫

    package com.yancheng.shack;


    import java.io.IOException;

    import java.util.HashMap;

    import android.app.Activity;

    import android.media.AudioManager;

    import android.media.SoundPool;

    import android.os.Bundle;

    import android.os.Vibrator;

    import android.view.animation.Animation;

    import android.view.animation.Animation.AnimationListener;

    import android.view.animation.AnimationSet;

    import android.view.animation.TranslateAnimation;

    import android.widget.RelativeLayout;

    import android.widget.Toast;

    import com.yancheng.shack.ShakeListener.OnShakeListener;


    public class MainActivity extends Activity {

    private final int DURATION_TIME = 600;


    private ShakeListener mShakeListener = null;


    private Vibrator mVibrator;


    private RelativeLayout mImgUp;


    private RelativeLayout mImgDn;


    private SoundPool sndPool;

    private HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();


    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    initView();

    mVibrator = (Vibrator) getApplication().getSystemService(

    VIBRATOR_SERVICE);

    // 檢查設備是否有震動裝置

    // mVibrator.hasVibrator();

    loadSound();

    mShakeListener = new ShakeListener(this);

    // 監聽到手機搖動

    mShakeListener.setOnShakeListener(new OnShakeListener() {

    public void onShake() {

    startAnim();

    }

    });

    }


    /****

    * 初始化控件

    */

    private void initView() {

    // TODO Auto-generated method stub

    mImgUp = (RelativeLayout) findViewById(R.id.shakeImgUp);

    mImgDn = (RelativeLayout) findViewById(R.id.shakeImgDown);

    }


    /****

    * 獲取音效

    */

    private void loadSound() {

    sndPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);

    new Thread() {

    public void run() {

    try {

    soundPoolMap.put(

    0,

    sndPool.load(

    getAssets().openFd(

    "sound/shake_sound_male.mp3"), 1));


    soundPoolMap.put(1, sndPool.load(

    getAssets().openFd("sound/shake_match.mp3"), 1));

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }.start();

    }


    public void startAnim() {

    AnimationSet animup = new AnimationSet(true);

    TranslateAnimation mytranslateanimup0 = new TranslateAnimation(

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,

    -0.5f);

    mytranslateanimup0.setDuration(DURATION_TIME);

    TranslateAnimation mytranslateanimup1 = new TranslateAnimation(

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,

    +0.5f);

    mytranslateanimup1.setDuration(DURATION_TIME);

    mytranslateanimup1.setStartOffset(DURATION_TIME);

    animup.addAnimation(mytranslateanimup0);

    animup.addAnimation(mytranslateanimup1);

    mImgUp.startAnimation(animup);


    AnimationSet animdn = new AnimationSet(true);

    TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,

    +0.5f);

    mytranslateanimdn0.setDuration(DURATION_TIME);

    TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,

    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,

    -0.5f);

    mytranslateanimdn1.setDuration(DURATION_TIME);

    mytranslateanimdn1.setStartOffset(DURATION_TIME);

    animdn.addAnimation(mytranslateanimdn0);

    animdn.addAnimation(mytranslateanimdn1);

    mImgDn.startAnimation(animdn);


    // 動畫監聽,開始時顯示加載狀態,

    mytranslateanimdn0.setAnimationListener(new AnimationListener() {


    @Override

    public void onAnimationStart(Animation animation) {

    mShakeListener.stop();

    sndPool.play(soundPoolMap.get(0), (float) 0.2, (float) 0.2, 0,

    0, (float) 0.6);

    }


    @Override

    public void onAnimationRepeat(Animation animation) {


    }


    @Override

    public void onAnimationEnd(Animation animation) {

    Toast.makeText(getBaseContext(), "搖一搖結束", Toast.LENGTH_SHORT)

    .show();

    mShakeListener.start();

    }

    });

    }


    @Override

    protected void onDestroy() {

    // TODO Auto-generated method stub

    super.onDestroy();

    if (mShakeListener != null) {

    mShakeListener.stop();

    }

    }

    }

  3. 搖一搖監聽事件

    package com.yancheng.shack;


    import android.content.Context;

    import android.hardware.Sensor;

    import android.hardware.SensorEvent;

    import android.hardware.SensorEventListener;

    import android.hardware.SensorManager;


    /**

     * 搖一搖監聽事件

     * @created 2014-08-19

     * @author 

     *

     */

    public class ShakeListener implements SensorEventListener {

    private static final int SPEED_SHRESHOLD = 4500;//這個值越大需要越大的力氣來搖晃手機

    private static final int UPTATE_INTERVAL_TIME = 50;

    private SensorManager sensorManager;

    private Sensor sensor;

    private OnShakeListener onShakeListener;

    private Context mContext;

    private float lastX;

    private float lastY;

    private float lastZ;

    private long lastUpdateTime;


    public ShakeListener(Context c) {

    mContext = c;

    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);

    }


    public void setOnShakeListener(OnShakeListener listener) {

    onShakeListener = listener;

    }


    public void onSensorChanged(SensorEvent event) {

    long currentUpdateTime = System.currentTimeMillis();

    long timeInterval = currentUpdateTime - lastUpdateTime;

    if (timeInterval < UPTATE_INTERVAL_TIME)

    return;

    lastUpdateTime = currentUpdateTime;


    float x = event.values[0];

    float y = event.values[1];

    float z = event.values[2];


    float deltaX = x - lastX;

    float deltaY = y - lastY;

    float deltaZ = z - lastZ;


    lastX = x;

    lastY = y;

    lastZ = z;


    double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ

    * deltaZ)

    / timeInterval * 10000;

    if (speed >= SPEED_SHRESHOLD) {

    onShakeListener.onShake();

    }

    }


    public void onAccuracyChanged(Sensor sensor, int accuracy) {


    }


    public interface OnShakeListener {

    public void onShake();

    }


    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章