智能检测应用程序背景
我正在寻找一种方法来检测我的Android应用程序是否已进入后台,以便无论按下Home键(或堆栈中最后一个活动的返回键)时运行哪个Activity
,然后将调用指定的函数。
onPause()
和 onStop()
无法区分替换当前活动的新活动和正在后台运行的应用程序,因此我正在寻求有关哪些额外测试的建议( s) 我必须包括以确定这一点。
I'm looking for a way to detect that my android app has been backgrounded, so that regardless of which Activity
was running upon pressing the Home key (or return key on the last activity in stack) then a specified function will be called.
onPause()
and onStop()
cannot distinguish between a new activity replacing the current one and the app being backgrounded, so I'm looking for advice as to what additional test(s) I must include to ascertain this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如其他人所建议的那样,使用服务是正确的做法。
一般来说,组成应用程序的不同 Activity 都应该在其
onResume()
方法中绑定到服务。他们应该在onPause()
处解除与服务的绑定。当所有先前连接的客户端都断开连接时,您的服务的
onUnbind()
方法将被调用,此时您将断开蓝牙连接。有关服务以及从活动绑定到服务的更多信息,请访问 http://developer。 android.com/reference/android/app/Service.html。
Using a service, as others have suggested, is the right thing to do.
Broadly, the different Activities that make up your application should all bind to the service in their
onResume()
method. They should unbind from the service atonPause()
.Your service's
onUnbind()
method will be called when there all the previously connected clients have disconnected, which would be the point where you would drop the Bluetooth connection.More information about services, and binding to them from activities, at http://developer.android.com/reference/android/app/Service.html.