Dmitry Frank
Dmitry Frank

Reputation: 10757

Android: how to get a pointer to the Service?

I have application with a Service. This service starts worker Thread, and this thread needs a pointer to an instance of Service (it calls some methods of this service).

Now i just pass this pointer from Service's onCreate() method to my own Runnable constructor, but it works correctly until i close my app. When app is restarted, something becomes really wrong with pointers. I still can't figure out what especially is wrong, but it seems like pointer to my instance of Service is a pointer to strange another instance of Service, and pointer to my Runnable is wrong too.

If i kill my app, then next time it works correctly, but after restart the same issues is taking place.

I suspect that i can't pass this pointer from onCreate() method of Service, but then, how can i get pointer to instance of my Service from the thread that starts from onCreate() method?

UPDATE: I just figured out that i have exactly the same singleton issue. The Runnable was a singleton. But i still can't find any good solution except not to use singletons in Android at all. Maybe, any suggestions?

Upvotes: 1

Views: 381

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006644

this thread needs a pointer to an instance of Service (it calls some methods of this service).

There are no pointers in Java. The Java equivalent would be "object reference".

until i close my app

There is no such concept as "closing" an "app" in Android.

I still can't figure out what especially is wrong, but it seems like pointer to my instance of Service is a pointer to strange another instance of Service, and pointer to my Runnable is wrong too.

That is eminently possible, if you stopped the original Service and leaked the thread, then started up the Service again. You may well have wound up with two threads, one holding a defunct copy of your Service.

how can i get pointer to instance of my Service from the thread that starts from onCreate() method?

That is not your problem. Your problem, whatever it is, lies elsewhere.

Upvotes: 1

Related Questions