如何获取Android本地服务实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3025299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:21:27  来源:igfitidea点击:

How to get Android Local Service instance

androidservice

提问by Henrik

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

我正在使用 startService 在我的应用程序中启动一个服务。

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

我不想使用 bindService 因为我想自己处理使用寿命。

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.

如果不使用 bindService,如何启动服务的实例?我希望能够获得我在服务类中创建的处理程序来发布来自活动的消息。

Thanks.

谢谢。

/ Henrik

/ 亨里克

采纳答案by CommonsWare

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

我不想使用 bindService 因为我想自己处理使用寿命。

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

这并不意味着您必须避免bindService(). 如果需要,同时使用startService()bindService()

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

如果不使用 bindService,如何启动服务的实例?

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

要么使用bindService()with startService(),要么使用单例。

回答by Brodo Fraggins

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.Binderand 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.

onServiceConnected(...)可以将其参数转换为MyService.Binder并调用getService()它。这避免了由于对服务的静态引用而导致的潜在内存泄漏。当然,您仍然必须确保您的活动没有挂在参考上。