Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i will detect motion sensor in broadcast receiver?

Tags:

I had written one receiver to detect device motion is changed or not like this in Manifest.xml

 <receiver android:name="com.hanuman.sensor.receiver.SensorReceiver" >
            <intent-filter
                android:enabled="true"
                android:exported="false" >
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>

and inside receiver onReceive() method code is:

String action = intent.getAction();
        if (action.equals(Intent.ACTION_USER_PRESENT)) {
            System.out.println("User is present");
            Intent s = new Intent(context, MainActivity.class);
            s.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(s);
        } else {
            System.out.println("User is not present");
        }

finally my question is, is not detecting the sensor when it is motioned, it is detecting when my device in unlocked then it is calling my MainActivity, but i want to detect when my device motion is changed then i want to detect in receiver. How can i do that?.

like image 296
Hanuman Avatar asked Apr 13 '15 11:04

Hanuman


People also ask

Does broadcast receiver work in background?

A broadcast receiver will always get notified of a broadcast, regardless of the status of your application. It doesn't matter if your application is currently running, in the background or not running at all.

How can I get sensor data in Android?

You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks.


1 Answers

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-

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
    //do some stuff
    }
    //do some other code for other Sensor type
    }
like image 183
Mohit Rajput Avatar answered Oct 05 '22 17:10

Mohit Rajput