短视频平台源码安卓简单实现微信摇一摇

java代码:

package com.example.day09;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Toast;

public class Main3Activity extends AppCompatActivity implements SensorEventListener {
    SensorManager manager;
    ImageView up;
    ImageView down;
    Sensor sensor;
    private Vibrator vibrator;
    private SoundPool soundPool;
    private TranslateAnimation animationup;
    private TranslateAnimation animationdown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        up = findViewById(R.id.img_up);
        down = findViewById(R.id.img_down);
        initService();
    }

    private void initService() {
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        //初始化震动
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        //初始化音乐  最大数量 播放的类型 质量
        soundPool = new SoundPool(5,AudioManager.STREAM_MUSIC,0);
        soundPool.load(this,R.raw.wx,1);
        //初始化动画
         animationup = new TranslateAnimation(0,0,0,-200);
         animationdown = new TranslateAnimation(0,0,0,-200);
}

    @Override
    protected void onResume() {
        super.onResume();
        manager.registerListener(this,sensor,200);
    }

    @Override
    protected void onPause() {
        super.onPause();
        manager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        //实现摇一摇的逻辑
        float[] values = event.values;
        float x = values[0];
        float y = values[1];
        float z = values[2];

        if(Math.abs(x) > 15||Math.abs(y) > 15||Math.abs(z) > 15){
            long[] patten = {300,500};
            vibrator.vibrate(patten,-1);
            soundPool.play(1,1,1,1,1,1);
            //播放动画
            up.startAnimation(animationup);
            down.startAnimation(animationdown);
            Toast.makeText(this, "摇一摇", Toast.LENGTH_SHORT).show();
        }

    }

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

    }
}

你可能感兴趣的:(技术类,animation,silverlight,android,安卓,framework)