0

I can see how I'd save things like simple integers and wot-not, but, for instance, if my main activity is communicating with a Service, I'll have a Handler instance I created stashed in a class member. What do I do about saving complicated objects like that? How do I get back in touch with my Service? (Probably the content of this question proves that I am indeed confused, but I'm hoping someone will humor me :-).

Apparently I need to make my confusion clearer. Let's try an example. I have a class member initialized like so:

private final Handler mHandler = new Handler() {...yadda, yadda};

I've passed it to a Service that is using it to send back messages to my main activity. What will make that same handler instance still be there in my activity when I (for instance) rotate the screen?

Likewise for the mTalkService class member that came from

new AardTalkerService(this, mHandler);

which is the service itself, what makes it possible for me to be using mTalkService after a save/restore of state?

Eric
  • 95,302
  • 53
  • 242
  • 374
user1160711
  • 463
  • 1
  • 5
  • 11
  • There are much better (*proper*) ways to communicate with a Service. Look at this question: http://stackoverflow.com/a/2463746/489607 – davidcesarino Jun 27 '12 at 23:06
  • Hey, I'm just modifying the BluetoothChat example, don't blame me for improper code :-). Looks like there is lots of info to digest here now. Thanks everybody! – user1160711 Jun 27 '12 at 23:27

3 Answers3

0

Make it a class field and initialize it in the OnCreate() method, that way you can use it almost anywhere in your application.

Jack Satriano
  • 1,999
  • 1
  • 13
  • 17
0

Don't use direct access to the Activity class members, because it gets killed and recreated often enough to guarantee your app will eventually crash and burn.

You may use broadcast receivers or Observable/Observer pattern, where your Activity registers as Observer in onRestore() and unregisters in onPause(), to make sure nobody tries to send updates to a dead Activity.

lenik
  • 23,228
  • 4
  • 34
  • 43
0

Really cool way (it really depends on what 'cool' mean to you ;) ) to do this is to create a class that inherits from android.app.Application and add your field there. So when you ask for the Context, from anywhere in the app, you will get an instance of this class, and you can access your field.

(NOTE::: You need to register your custom implementation in the manifest for this to work.)

Otherwise, if you want it simple, quick and dirty, simply have a static class, have a static field, and access it from your service and activity(ies). (Look out for thread synchronization issues)

If your service and activity runs on the same process, you can use a custom interface, which got a simple callback, which can be subscribed from your activity, instead of going through the trouble of Handlers.

Madushan
  • 6,977
  • 31
  • 79