pressing the back button on android through service

爱⌒轻易说出口 提交于 2019-12-12 05:02:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!