I am developing an app which is basically one widget and one service. The widget is only a button which I want it to run the service in the device's background. So the user just clicks the button and nothing happens in the UI, the service starts in the background. But I want the background service, which I have implemented using IntentService, to ALWAYS listen to my device's shake in the background after the widget's button is clicked. It has to monitor the accelerometer sensor for any change at any time. Finally I want to open a certain application if the user shakes his device.
I have implemented the widget part, I click the button and the service runs. I have also implemented the shake part, I can get the shake and do some stuff after the shake. I also know how to open another application after the shake. I just can't do this through the service! So my question is this:
I have reviewed this question: ["Shake" app to respond at any time ] but I didn't get the details of how the service listens in the background.
Can anyone help?
You can use both Service
and IntentService
. Here I have given one of the method which should work for you. For difference between Service
and IntentService
follow this link.
public class service extends Service implements SensorEventListener {
@Override
public void onCreate() {
super.onCreate();
//register your sensor manager listener here
}
@Override
public void onDestroy() {
//unregister your listener here
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
//detect the shake and do your work here
}
}