• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing Secondary UI Thread

 
George Willis
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing an app for the purpose of studying threads using timers. I've created an IntentService that runs a CountDownTimer for 5 seconds (Button b2) while a secondary UI thread runs as a type of stopwatch. I would like to take readings from the stopwatch to post Countdown start and stop times to a TextView (logView) in the Activity but I'm having trouble figuring out a way to access the secondary UI thread to grab the split times. Any help is appreciated.
Here is my Activity code:
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I generally prefer to use AsyncTask over Handler, but that is to some degree a matter of personal choice.

My preferred approach to distributing data across various components of an app (and across multiple threads) is the https://github.com/greenrobot/EventBus/ library. I think it's an elegant solution to avoid close coupling between classes that otherwise have nothing to do with one another.
 
George Willis
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I look forward to the day when I examine EventBus, or Guava, or Otto. Right now I'm trying to look at the nuts and bolts. IntentService seemed like the easiest place to start. For IntentService I do like that you can simply place some text in a putExtra (with no other info being sent) so that a flag can be signaled, especially on the MainActivity side, that whatever you wanted to do in thread 2 (in this case wait 5 seconds and then signal back) is complete. My intended 2nd thread in MainActivity was misconceived. I would have had to explicitly started another thread. I still needed the handler to make the Stopwatch(or timerRunnable) work. Since my timerHandler is created inside the MainActivity it handles messaging for that activities thread. It appears that there is something of a handler already present in a MainActivity to 'handle' its communication. I found this article useful, and nothing like it elsewhere. But, I would be interested in any similar info if anyone can provide it:
Android MainActivity Framework

Accessing info inside my StopWatch was as simple as making a variable public.

Here is my resultant code. I hope I'm not violating any 'max lines of code rules':
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic