Android ==> Service question?
I have a service running on my android application, the service is a socket class that has to run through the whole application, i create it when my first activity loads. How can i get an instance of this socket class so that i can call a function in this class.
For example
//how can i get an instance of the running service?
MyService s = getService();
s.writeDataToSer开发者_如何学Cver("hello");
There's two ways you can go about doing this depending on if you want to keep the socket open when the user isn't actively using your UI.
The first is a LocalService
it's the same as a regular Service
except it runs in the same process as your Activity
s UI thread and therefore you can gain a direct reference to it. This is a much lighter method of creating and using a Service than using AIDL. I only recommend using AIDL if you wish to create an out-of-process service that needs to be accessed either by different processes in your application or in different applications. This is most likely not what you need. The LocalService method will allow you to keep the service running in the background and in turn keep the socket open even when the UI isn't in use.
If you don't have the requirement of keeping the socket open and only wish to have access to it from multiple Activity
s then you can extend the Application
class and register it in your manifest. It allows you to manage global application state. You can put the socket creation and management functions into that class and then provide methods for your various Activity
s to gain access to it. The Application
class dies when the process dies so it is not suitable for keeping a socket open for long periods of time or during times when the user is not actively using your application.
There is the built in Activity#getApplication()
method that helps with this process. You can specify your custom Application
class in the AndroidManifest.xml via the android:name
attribute.
The Android Interface Definition Language (AIDL) is the correct way to connect to a service.
Check out http://developer.android.com/guide/developing/tools/aidl.html
For information how to communicate with a service.
Check out Intents
and the bindService
method.
精彩评论