问题
Is it possible to programmatically press the back button on android through a service ?
I know I can override the onBackPressed() method if I were in an Activity, but I am looking for a solution that works for a service running in the background.
回答1:
Its not a good idea to have the service change the UI directly. You can send a broadcast from the service. Any activity which is open at that point, can listen to the broadcast and then decide to take appropriate action (in this case to close the app). You can simulate a key press from the activity.
回答2:
Is it possible to programmatically press the back button on android through a service ?
No.
I know I can override the onBackPressed() method if I were in an Activity,
That has nothing to do with "programmatically press the back button".
I am looking for a solution that works for a service running in the background.
Your service is welcome to send a message to your activity which causes the activity to call finish()
. You could use any of the following for such a message:
LocalBroadcastManager
- an event bus like Otto
- a regular broadcast
Intent
- a
Messenger
- etc.
However, if your expectation is that you will be able to attack the activities of other apps, forcing them to call finish()
, that is not possible.
来源:https://stackoverflow.com/questions/16430805/pressing-the-back-button-on-android-through-service