Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.content.Context;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.widget.Toast;
- public class MainActivity extends AppCompatActivity {
- //full information for sensor
- //https://guides.codepath.com/android/Listening-to-Sensors-using-SensorManager#sensors-in-the-background
- //TAG for log
- final static String TAG = "Sensor";
- //Sensor Managar to handle our all sensors
- private SensorManager sensorManager;
- //define sensor for light
- private Sensor flashLight;
- //create event listener to show when event that related to sensor has קרה
- private SensorEventListener sensorEventListener = new SensorEventListener() {
- @Override
- public void onSensorChanged(SensorEvent sensorEvent) {
- Toast.makeText(MainActivity.this, "onSensorChange:" + sensorEvent.toString(), Toast.LENGTH_LONG).show();
- Log.e(TAG, "onSensorChanged: " + sensorEvent.toString());
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int i) {
- Toast.makeText(MainActivity.this, "OnAccuracy changed:" + sensor.toString(), Toast.LENGTH_SHORT).show();
- Log.e(TAG, "onAccuracyChanged: " + sensor.toString());
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
- //get the defualt sensor of specific type
- flashLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
- }
- @Override
- protected void onPostResume() {
- super.onPostResume();
- if (flashLight != null) {
- sensorManager.registerListener(sensorEventListener, flashLight, SensorManager.SENSOR_DELAY_NORMAL);
- }
- }
- @Override
- protected void onPause() {
- if (flashLight != null) {
- sensorManager.unregisterListener(sensorEventListener);
- }
- super.onPause();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement