开发者

Message Handling, unexpected behavior with worker threads

开发者 https://www.devze.com 2023-03-10 16:02 出处:网络
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 me

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开发者_JS百科, 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.


Use sendBroadcast(), with the Activity registering a BroadcastReceiver for the broadcast via registerReceiver() in onResume() and unregistering it in onPause(). Then, it will only process the event if it is in the foreground.


Put some flag in onPause() method of activity that starts the thread to indicate that it is not foreground anymore. In onStart() reverse the flag.

When it is a time to display dialog, check this flag and only show dialog if activity is running.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号