How i will detect motion sensor in broadcast receiver? How i will detect motion sensor in broadcast receiver? android android

How i will detect motion sensor in broadcast receiver?


Get object of SensorManager like below-

SensorManager sensorMan = (SensorManager)getSystemService(SENSOR_SERVICE);Sensor sensor = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Register listener to listen changes in motion sensor-

sensorMan.registerListener(context, sensor,        SensorManager.SENSOR_DELAY_UI);

Then override onSensorChanged() method to detect changes-

@Overridepublic void onSensorChanged(SensorEvent event) {    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){    //do some stuff    }    //do some other code for other Sensor type    }


You cannot and you should not do that, because when the screen goes off the sensor's gone off automatically, this is done by the system in most of the devices, some devices support sensors listening after the screen goes off like nexus 4.But you can create the receivers that will listen to screen off and screen on.

public class Screen extends BroadcastReceiver {

    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {            screenOn();        }        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {            screenOff();        }    }    IntentFilter intentFilter = new IntentFilter();    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);    intentFilter.addAction(Intent.ACTION_SCREEN_ON);    mReceiver = new Screen();    registerReceiver(mReceiver, intentFilter);