Android学习笔记:摇一摇功能的实现

Posted 纯属浪费8818

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android学习笔记:摇一摇功能的实现相关的知识,希望对你有一定的参考价值。

 

首先需要用到一个摇一摇的工具类

 

ShakeManager.java

 1 package com.wuxianedu.oschina.utils;
 2 
 3 import android.content.Context;
 4 import android.hardware.Sensor;
 5 import android.hardware.SensorEvent;
 6 import android.hardware.SensorEventListener;
 7 import android.hardware.SensorManager;
 8 
 9 /**
10  * 震动监听器
11  */
12 public class ShakeManager implements SensorEventListener {
13 
14     private Context mContext;
15     private static final int SPEED_SHRESHOLD = 4500;//这个值越大需要越大的力气来摇晃手机
16     private static final int UPTATE_INTERVAL_TIME = 50;
17     private SensorManager sensorManager;
18     private Sensor sensor;
19     private ShakeListener shakeListener;
20     private float lastX;
21     private float lastY;
22     private float lastZ;
23     private long lastUpdateTime;
24 
25     public ShakeManager(Context c) {
26         mContext = c;
27         start();
28     }
29 
30     /**
31      * 启动
32      */
33     public void start() {
34         sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
35         if (sensorManager != null) {
36             sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
37         }
38         if (sensor != null) {
39             sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
40         }
41     }
42 
43     /**
44      * 停止
45      */
46     public void stop() {
47         sensorManager.unregisterListener(this);
48     }
49 
50     public void onSensorChanged(SensorEvent event) {
51         long currentUpdateTime = System.currentTimeMillis();
52         long timeInterval = currentUpdateTime - lastUpdateTime;
53         if (timeInterval < UPTATE_INTERVAL_TIME)
54             return;
55         lastUpdateTime = currentUpdateTime;
56 
57         float x = event.values[0];
58         float y = event.values[1];
59         float z = event.values[2];
60 
61         float deltaX = x - lastX;
62         float deltaY = y - lastY;
63         float deltaZ = z - lastZ;
64 
65         lastX = x;
66         lastY = y;
67         lastZ = z;
68 
69         double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
70                 * deltaZ)
71                 / timeInterval * 10000;
72         if (speed >= SPEED_SHRESHOLD) {
73             shakeListener.onShake();
74         }
75     }
76 
77     public void onAccuracyChanged(Sensor sensor, int accuracy) {}
78 
79     public void setShakeListener(ShakeListener shakeListener) {
80         this.shakeListener = shakeListener;
81     }
82 
83     public interface ShakeListener {
84         void onShake();
85     }
86 
87 }

 

接下来我们在MainActivity.java中来使用

 1     private ShakeManager shake;
 2 
 3         shake.setShakeListener(new ShakeManager.ShakeListener() {
 4             @Override
 5             public void onShake() {
 6                 QiStart();
 7                 shake.stop();
 8                 canrads.setVisibility(View.GONE);
 9                 soundPool.play(map.get(1),0.3f,0.3f,1,0,0);
10             }
11         });
12 
13 
14 
15     /**
16      * 开始动画
17      */
18     private void QiStart() {
19         TranslateAnimation up = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0f,Animation.RELATIVE_TO_SELF,0f
20                 ,Animation.RELATIVE_TO_SELF,0f,Animation.RELATIVE_TO_SELF,-0.3f);
21         up.setDuration(600L);
22         up.setRepeatCount(1);
23         up.setRepeatMode(Animation.REVERSE);
24         imageshang.startAnimation(up);
25 
26         TranslateAnimation down = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0f,Animation.RELATIVE_TO_SELF,0f
27                 ,Animation.RELATIVE_TO_SELF,0f,Animation.RELATIVE_TO_SELF,0.3f);
28         down.setDuration(600L);
29         down.setRepeatCount(1);
30         down.setRepeatMode(Animation.REVERSE);
31         imagexia.startAnimation(down);
32 
33         down.setAnimationListener(new Animation.AnimationListener() {
34             @Override
35             public void onAnimationStart(Animation animation) {
36 
37             }
38             @Override
39             public void onAnimationEnd(Animation animation) {
40                 xian2.setVisibility(View.VISIBLE);
41                 new RequestClient(getContext(),requestConfig){
42 
43                     @Override
44                     protected void loadSuccess(String result) {
45                         try {
46                             result = new String(result.getBytes("ISO-8859-1"),"UTF-8");
47                         } catch (UnsupportedEncodingException e) {
48                             e.printStackTrace();
49                         }
50                         shakeb = JSONParseUtil.parseObject(result,Shakeb.class);
51                         assert shakeb != null;
52                         String title = shakeb.getOwner()!=null ? shakeb.getOwner().getName():"";
53                         tv_neirong.setText(title);
54                         tv_biaoti.setText(shakeb.getDescription());
55                         tv_chakan.setText(String.valueOf(shakeb.getForks_count()));
56                         tv_xingxing.setText(String.valueOf(shakeb.getStars_count()));
57                         tv_disange.setText(String.valueOf(shakeb.getWatches_count()));
58                         //获取图片地址
59                         String imageUrl = shakeb.getOwner().getNew_portrait();
60                         ImageLoader imageLoader = ImageLoaderFactory.getImageLoader();
61                         //加载图片
62                         imageLoader.loadImage(imageUrl,roundImageView);
63                         //隐藏正在加载
64                         xian2.setVisibility(View.GONE);
65                         //播放声音
66                         soundPool.play(map.get(0),0.3f,0.3f,1,0,0);
67                         //显示推举项目
68                         canrads.setVisibility(View.VISIBLE);
69                         //摇一摇监听开始
70                         shake.start();
71                     }
72 
73                     @Override
74                     protected void loadFail() {
75 
76                     }
77                 }.get(RequestAPI.SHAKE);
78             }
79 
80             @Override
81             public void onAnimationRepeat(Animation animation) {
82 
83             }
84         });
85 
86     }
 /**
     * 判断Fragment是否可见
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            shake.stop();
        }else{
            shake.start();
        }
    }


true为不可见

 



以上是关于Android学习笔记:摇一摇功能的实现的主要内容,如果未能解决你的问题,请参考以下文章

手机端 摇一摇功能 代码实现

Android摇一摇振动效果Demo

Flutter 实现微信摇一摇的功能 Flutter 加速度感应

咸鱼教程Egret实现摇一摇功能

iOS之摇一摇功能实现

shake.js实现微信摇一摇功能