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.
精彩评论