質問

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:

  • Do I have to make my IntentService class implement SensorEventListener?
  • If yes, is only this implementation enough for it to listen to the sensor at all times? What should I do in onHandleIntent(Intent intent) then?!
  • All the sensor changes are going to be listened in onSensorChanged(SensorEvent sensorEvent) if it was implemented in a regular Activity. Does it mean that I have to put everything in that function? nothing in the onHandleIntent?
  • I also have this intent, comes from my widget to my service, which I don't know what to do with! I have started the intentService using that intent but if I don't use the onHandleIntent I can't pass setAction for my intent, so it would be useless!

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
    }

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top