SHOW:
|
|
- or go back to the newest paste.
1 | package com.example.teacher.mysensors; | |
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 | import android.support.v7.app.AppCompatActivity; | |
9 | import android.os.Bundle; | |
10 | import android.util.Log; | |
11 | import android.widget.Toast; | |
12 | ||
13 | public class MainActivity extends AppCompatActivity { | |
14 | ||
15 | //full information for sensor | |
16 | //https://guides.codepath.com/android/Listening-to-Sensors-using-SensorManager#sensors-in-the-background | |
17 | ||
18 | //TAG for log | |
19 | final static String TAG="Sensor"; | |
20 | //Sensor Managar to handle our all sensors | |
21 | private SensorManager sensorManager; | |
22 | //define sensor for light | |
23 | private Sensor flashLight; | |
24 | ||
25 | //create event listener to show when event that related to sensor has קרה | |
26 | private SensorEventListener sensorEventListener = new SensorEventListener() { | |
27 | @Override | |
28 | public void onSensorChanged(SensorEvent sensorEvent) { | |
29 | Toast.makeText(MainActivity.this, "onSensorChange:"+ sensorEvent.toString(), Toast.LENGTH_LONG).show(); | |
30 | Log.e(TAG, "onSensorChanged: "+sensorEvent.toString()); | |
31 | } | |
32 | ||
33 | @Override | |
34 | public void onAccuracyChanged(Sensor sensor, int i) { | |
35 | Toast.makeText(MainActivity.this, "OnAccuracy changed:"+sensor.toString(), Toast.LENGTH_SHORT).show(); | |
36 | Log.e(TAG, "onAccuracyChanged: "+sensor.toString() ); | |
37 | } | |
38 | }; | |
39 | ||
40 | @Override | |
41 | protected void onCreate(Bundle savedInstanceState) { | |
42 | super.onCreate(savedInstanceState); | |
43 | setContentView(R.layout.activity_main); | |
44 | sensorManager=(SensorManager)getSystemService(Context.SENSOR_SERVICE); | |
45 | //get the defualt sensor of specific type | |
46 | flashLight=sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); | |
47 | } | |
48 | ||
49 | @Override | |
50 | protected void onPostResume() { | |
51 | super.onPostResume(); | |
52 | if (flashLight!=null) | |
53 | { | |
54 | sensorManager.registerListener(sensorEventListener,flashLight,SensorManager.SENSOR_DELAY_NORMAL); | |
55 | } | |
56 | } | |
57 | ||
58 | @Override | |
59 | protected void onPause() { | |
60 | if (flashLight!=null) | |
61 | { | |
62 | sensorManager.unregisterListener(sensorEventListener); | |
63 | } | |
64 | super.onPause(); | |
65 | } | |
66 | } |