How to get Android Local Service instance

2020-04-02 06:00发布

I'm starting a service in my application using startService.

I do not want to use bindService as I want to handle the service life time myself.

How can I get an instance to the service started if I do not use bindService? I want to be able to get a handler I've created in the service class to post messages from the activity.

Thanks.

/ Henrik

2条回答
戒情不戒烟
2楼-- · 2020-04-02 06:34

I do not want to use bindService as I want to handle the service life time myself.

That does not mean you have to avoid bindService(). Use both startService() and bindService(), if needed.

How can I get an instance to the service started if I do not use bindService?

Either use bindService() with startService(), or use a singleton.

查看更多
对你真心纯属浪费
3楼-- · 2020-04-02 06:38

Here's another approach:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    private Binder binder;  

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new Binder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class Binder extends android.os.Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
}

onServiceConnected(...) can cast its argument to MyService.Binder and call getService() on it. This avoids the potential memory leak from having a static reference to the service. Of course, you still have to make sure your activity isn't hanging onto a reference.

查看更多
登录 后发表回答