android 检测摇一摇

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Manifest添加  <br><uses-permission android:name="android.permission.VIBRATE"/><br><br><br>package com.example.a;
 
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.Menu;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    private SensorManager smg;
    private Vibrator vbt;
    private static final int SENSOR_SHAKE=10;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        smg=(SensorManager)this.getSystemService(SENSOR_SERVICE);
        vbt=(Vibrator)this.getSystemService(VIBRATOR_SERVICE);
         
    }
    @Override
    public void onResume(){
        super.onResume();
        if(smg!=null){
            smg.registerListener(sensorEventListener, smg.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),smg.SENSOR_DELAY_NORMAL);
        }
    }
    @Override
    public void onPause(){
        super.onPause();
        if(smg!=null){
            smg.unregisterListener(sensorEventListener);
        }
    }
    private SensorEventListener sensorEventListener =new SensorEventListener(){
        public void onSensorChanged(SensorEvent event){
            float[] values =event.values;
            float x = values[0];
            float y = values[1];
            float z = values[2];
            System.out.println("x:"+x+"    y:"+y+"     z:"+z);
            int medumValue =15;
            if(Math.abs(x)>medumValue||Math.abs(y)>medumValue||Math.abs(z)>medumValue){
                vbt.vibrate(200);
                Message msg=new Message();
                msg.what=SENSOR_SHAKE;
                 
            }
        }
        public void onAccuracyChanged(Sensor sensor,int assuray){
             
        }
    };
    Handler handler=new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
            case SENSOR_SHAKE:
                Toast.makeText(getApplicationContext(), "I know you are shake your phone now", 2000).show();
            }
        }
    };
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
     
}

  

android 检测摇一摇,布布扣,bubuko.com

android 检测摇一摇

上一篇:Android使用百度地图API实现GPS步行轨迹


下一篇:有关ViewPager的使用及解决Android下ViewPager和PagerAdapter中调用notifyDataSetChanged失效的问题