Advertisement
amjadArabia

Sensor {flashLight}

Nov 14th, 2017
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. import android.content.Context;
  2. import android.hardware.Sensor;
  3. import android.hardware.SensorEvent;
  4. import android.hardware.SensorEventListener;
  5. import android.hardware.SensorManager;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.os.Bundle;
  8. import android.util.Log;
  9. import android.widget.Toast;
  10.  
  11. public class MainActivity extends AppCompatActivity {
  12.  
  13.     //full information for sensor
  14.     //https://guides.codepath.com/android/Listening-to-Sensors-using-SensorManager#sensors-in-the-background
  15.  
  16.     //TAG for log
  17.     final static String TAG = "Sensor";
  18.     //Sensor Managar to handle our all sensors
  19.     private SensorManager sensorManager;
  20.     //define sensor for light
  21.     private Sensor flashLight;
  22.  
  23.     //create event listener to show when event that related to sensor has קרה
  24.     private SensorEventListener sensorEventListener = new SensorEventListener() {
  25.         @Override
  26.         public void onSensorChanged(SensorEvent sensorEvent) {
  27.             Toast.makeText(MainActivity.this, "onSensorChange:" + sensorEvent.toString(), Toast.LENGTH_LONG).show();
  28.             Log.e(TAG, "onSensorChanged: " + sensorEvent.toString());
  29.         }
  30.  
  31.         @Override
  32.         public void onAccuracyChanged(Sensor sensor, int i) {
  33.             Toast.makeText(MainActivity.this, "OnAccuracy changed:" + sensor.toString(), Toast.LENGTH_SHORT).show();
  34.             Log.e(TAG, "onAccuracyChanged: " + sensor.toString());
  35.         }
  36.     };
  37.  
  38.     @Override
  39.     protected void onCreate(Bundle savedInstanceState) {
  40.         super.onCreate(savedInstanceState);
  41.         setContentView(R.layout.activity_main);
  42.         sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  43.         //get the defualt sensor of specific type
  44.         flashLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
  45.     }
  46.  
  47.     @Override
  48.     protected void onPostResume() {
  49.         super.onPostResume();
  50.         if (flashLight != null) {
  51.             sensorManager.registerListener(sensorEventListener, flashLight, SensorManager.SENSOR_DELAY_NORMAL);
  52.         }
  53.     }
  54.  
  55.     @Override
  56.     protected void onPause() {
  57.         if (flashLight != null) {
  58.             sensorManager.unregisterListener(sensorEventListener);
  59.         }
  60.         super.onPause();
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement