forked from hussien89aa/AndroidTutorialForBeginners
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sensor accelerometer.txt
69 lines (50 loc) · 1.79 KB
/
Sensor accelerometer.txt
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
//permission
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
//code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor sensor;
SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
@Override
public void onResume(){
super.onResume();
sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onPause(){
super.onPause();
sensorManager.unregisterListener(this);
}
float xOld=0;
float yOld=0;
float zOld=0;
float ThreaShold=3000;
long OldTime=0;
@Override
public void onSensorChanged(SensorEvent event) {
float x =event.values[0];
float y =event.values[1];
float z =event.values[2];
long CurrentTime= System.currentTimeMillis();
if ((CurrentTime-OldTime)>100){
long TimeDiff=CurrentTime-OldTime;
OldTime=CurrentTime;
float speed=Math.abs(x+y+z-xOld-yOld-zOld)/TimeDiff *10000;
if (speed>ThreaShold){
Vibrator v=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
Toast.makeText(getApplicationContext(),"Shook",Toast.LENGTH_LONG).show();;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}