How to use Proximity Sensor in Android Programming - android

I know that there are only two values of proximity : 0.0 & 1.0
I need a simple code to detect proximity through the device's sensors, and perform any task if proximity changes to 1.0

this is what i found.
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_screen);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
iv = (ImageView) findViewById(R.id.imageView1);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (event.values[0] == 0) {
iv.setImageResource(R.drawable.near);
} else {
iv.setImageResource(R.drawable.far);
}
}
}

You can use the getMaximumRange() method to obtain your proximity sensor's max range and use it to determine what to do.
SensorManager sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
float maxRange = proximitySensor.getMaximumRange();
Now use maxRange to do what you want to do.
public void onSensorChanged(SensorEvent event) {
if(maxRange == event.values[0]) {
// Do something when something is far away.
}
else {
// Do something when something is near.
}
}
One very important thing. The proximity sensor varies from device to device. It not always reports 1.0 and 0.0. For example my Moto G (1st Gen.) reports 3 cm as its min range and 100 cm as its max range. So its best to obtain the max range of the device's sensor and use it in your code rather then hard-coding the value.

Related

How to read accelelrometer sensor values continously for 5 seconds inside an AccessibilityService?

I am using AccessibilityService to monitor whenever the foreground activity is changed. Additionally whenever a such a change occurs, I need to read the accelerometer readings for the next 5 seconds. I implemented the following code, but I am not getting continuous readings. Sometimes No reading is shown in between 2 app switches
I am able to detect the foreground activity change accurately, and I can run an activity independently that can show the sensor state changes. But problem exists in combining both.
public class WindowChangeDetectingService extends AccessibilityService implements SensorEventListener {
#Override
protected void onServiceConnected() {
...
}
SensorManager mSensorManager;
Sensor mAccelerometerSensor;
SensorEventListener mListener;
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
try {
mSensorManager.unregisterListener(mListener);
}
catch (Exception e){
Log.d("not unregs",e.toString());
}
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// do stuff with sensor values
mSensorManager.unregisterListener(mListener);
}
}, 5000);
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity)
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
#Override
public void onInterrupt() {}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
Log.i("\nAccelerometer: \n","X:"+x+"\tY:"+y+"\tZ:"+z);
}
}
Use SENSOR_DELAY_GAME or SENSOR_DELAY_FASTEST instead of SENSOR_DELAY_NORMAL
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this,
mAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME);//change here

How to get the brightness level from the camera Android

I want to get the brightness level from the Android camera.
I need to display the light level detected by the Android camera, is there any posibility to do that ?
private final SensorManager mSensorManager;
private final Sensor mLightSensor;
private float mLightQuantity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Obtain references to the SensorManager and the Light Sensor
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
// Implement a listener to receive updates
SensorEventListener listener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
lightQuantity = event.values[0];
}
}
// Register the listener with the light sensor -- choosing
// one of the SensorManager.SENSOR_DELAY_* constants.
sensorManager.registerListener(
listener, lightSensor, SensorManager.SENSOR_DELAY_UI);
}

How to detect the turnover motion in android?

If the user turns over the phone I want to react to that by stopping my text to speech reading. It would be a nice feature for my app, but how can I detect this motion? I'm not really familiar with motion sensors and I could not find this specific motion listener anywhere, mostly just screen orientations. Thanks for the help!
This sample activity demonstrates how a device's gravity sensor can be used to detect when the device is turned over. In method onSensorChanged(), term factor determines how complete the "turn over" must be. Typical range might be 0.7 to 0.95.
Support for Gravity Sensor was added in Android API 9. Not all devices have a gravity sensor.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "Demo";
private SensorManager mSensorManager;
private Sensor mGravitySensor;
private boolean mFacingDown;
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// nothing
}
#Override
public void onSensorChanged(SensorEvent event) {
final float factor = 0.95F;
if (event.sensor == mGravitySensor) {
boolean nowDown = event.values[2] < -SensorManager.GRAVITY_EARTH * factor;
if (nowDown != mFacingDown) {
if (nowDown) {
Log.i(TAG, "DOWN");
} else {
Log.i(TAG, "UP");
}
mFacingDown = nowDown;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mGravitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
if (mGravitySensor == null) {
Log.w(TAG, "Device has no gravity sensor");
}
}
#Override
protected void onResume() {
super.onResume();
if (mGravitySensor != null) {
mSensorManager.registerListener(this, mGravitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
}

How to Use Rotation Sensor in Android

I have a ball (bitmap) at the center of black surface View.
I want to move that ball to left of the screen, if we tilt the phone toward left.
Similarly for right side.
(Eg :- we control bike, in any bike racing android game).
Which sensor to use and how to gets its value.
The Code So Far......
public class ABC implements SensorEventListener {
public ABC(Context context){
sensormanager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
sensor = sensormanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensormanager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
.
some Code
.
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
#Override
public void onSensorChanged(SensorEvent arg0) {
}
}
You need to implement your code under onSensorChanged.
See example here:
#Override
public void onSensorChanged(SensorEvent arg0) {
float[] values = arg0.values;
// getting movement from x,y,z axis
float x = values[0];
float y = values[1];
float z = values[2];
}
Every time the sensor detects movement you get new values under the values[] array.
Now, you can use those values to do whatever you want.
It is good practice to register the listener under onResume() and unregister it under onPause(), like so:
#Override
protected void onResume() {
super.onResume();
// register the listener
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
Hope this has helped.
You'll have to use the GYROSCOPE, not the ACCELEROMETER.
The Gyroscope tells you about the rotation around X, Y, Z axis.
Also have a look at the SensorManager.getRotationMatrix() method.

How to use get Android's acceleration with specified times?

I am a java newer,
I want to get, for example, 10 different values of my phone's acceleration,
and get an average value from them.
But I can only find answers for continued data, or only one data.
Now I can get one data and display it on my screen.
Can I use for loop to calculate for 10 times?
Thank you.
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
aAngle = event.values[0];
bAngle = event.values[1];
}
private Button.OnClickListener listener = new Button.OnClickListener() {
switch(viewMode){
case VIEW_MODE_1:
title.setText(Double.toString(aAngle) + " " + Double.toString(bAngle));
break;}
I've tried to cast a for loop in the OnSensorChanged method, but it didn't work at all.
I tried to do this, but it seems to have a runtime error.
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0 && sensors.size() <= 10) {
sensorManager.registerListener(this,sensors.get(count),SensorManager.SENSOR_DELAY_NORMAL);
count ++;
}
also, I create two list to save the result every time when my angle is changed.
for(int i = 0; i < aAngleList.size(); i++){
double aAngleTotal = 0;
double bAngleTotal = 0;
aAngleTotal += aAngleList.get(i);
bAngleTotal += bAngleList.get(i);
aAngleAverage = aAngleTotal / aAngleList.size();
bAngleAverage = bAngleTotal / bAngleList.size();
}
public void onSensorChanged(SensorEvent event) {
aAngleList.add(aAngle);
bAngleList.add(bAngle);
}
the for loop is in onResume, right under the if (sensors...)
onSensorChanged is fired everytime your sensor gets a new reading. you can place a counter for ten changes. keep track of values in a list,hashmap and aggregate them.
public class SensorActivity extends Activity, implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private int count=0;
private List<String> eventX=new ArrayList<String>();
public SensorActivity() {
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
eventX.add(event.getValueMethodwhateverItis());
count++;
if (count=10){
//aggregate from list do anything you want.;
}
}
}

Categories

Resources