消息处理、工作线程的意外行为
我正在尝试一个带有后台服务的大型程序,并且正在使用基本的处理程序对象实现一个(相当不周密的)消息处理过程。该应用程序有一个主菜单,其中的按钮可启动 6 种不同的活动。
问题是这样的:如果我启动一个工作线程来启动对数据库的查询并检索一些数据,并且我关闭启动上述工作线程的活动,则活动中的处理程序仍然尝试运行并显示一个对话框,甚至尽管创建它的活动现在已完成(或未获得焦点)。在提交任何 (UI) 更改之前,如何判断当前活动是否处于焦点状态?
我最终通过简单地将“showDialog()”调用放在 try 语句中来解决了这个问题,但我想要一个更复杂的解决方案,因为这似乎是错误的做事方式。
I'm taking a stab at a large program with a background Service and I'm implementing a (rather poorly thought out) Message handling procedure using basic Handler objects. The application has a main menu with buttons which start 6 different activities.
Problem is this: if i start a worker thread which kicks off a query to the database and retrieves some data, and I close the Activity that started the aforementioned worker thread, the Handler in the Activity still tries to run and show a dialog, even though the Activity that created it is now finished (or not in focus). How can I tell whether the current Activity is in focus before committing any (UI) changes?
I ended up solving the issue by simply putting the 'showDialog()' call in a try statement, but i'd like a more sophisticated solution, as this just seems like the wrong way to do things.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
sendBroadcast()
,Activity
通过中的
并在registerReceiver()
注册用于广播的BroadcastReceiver
onResume()onPause()
中取消注册。然后,它只会处理位于前台的事件。Use
sendBroadcast()
, with theActivity
registering aBroadcastReceiver
for the broadcast viaregisterReceiver()
inonResume()
and unregistering it inonPause()
. Then, it will only process the event if it is in the foreground.在启动线程的 Activity 的 onPause() 方法中放置一些标志,以指示它不再是前台。在
onStart()
中反转标志。当需要显示对话框时,请选中此标志,并且仅在活动正在运行时才显示对话框。
Put some flag in
onPause()
method of activity that starts the thread to indicate that it is not foreground anymore. InonStart()
reverse the flag.When it is a time to display dialog, check this flag and only show dialog if activity is running.