How to have Android Service communicate with Activity

前端 未结 13 1884
说谎
说谎 2020-11-22 02:54

I\'m writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background an

13条回答
  •  温柔的废话
    2020-11-22 03:19

    There are three obvious ways to communicate with services:

    1. Using Intents
    2. Using AIDL
    3. Using the service object itself (as singleton)

    In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():

    void onCreate(Intent i) {
      sInstance = this;
    }
    

    Make a static function MyService getInstance(), which returns the static sInstance.

    Then in Activity.onCreate() you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread().

    The last thing you need to do is to remove the reference to you listener object in Activity.onPause(), otherwise an instance of your activity context will leak, not good.

    NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.

提交回复
热议问题