首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在bindService之前等待startService

在bindService之前等待startService
EN

Stack Overflow用户
提问于 2011-08-01 16:58:55
回答 2查看 1.7K关注 0票数 6

我的理解是,如果我想要一个服务运行,即使没有绑定到它,那么它必须首先使用startService(Intent i)启动。

我的问题是,如果我想在启动服务后立即绑定到它,下面的代码能保证服务是用startService()创建的吗?

服务类中的静态方法:

代码语言:javascript
复制
public static void actStart(Context ctx) {
    Intent i = new Intent(ctx, BGService.class);
    i.setAction(ACTION_START);
    ctx.startService(i);
}

绑定活动:

代码语言:javascript
复制
BGService.actionStart(getApplicationContext());    
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE);
EN

回答 2

Stack Overflow用户

发布于 2012-06-26 16:49:10

我不知道你在这里想做什么,但是"Context.BIND_AUTO_CREATE“创建服务,然后绑定到服务,即使它还没有启动。

现在,如果您想在绑定后立即访问它,可以使用serviceConnection的onServiceConnected()方法:

代码语言:javascript
复制
 new ServiceConnection() { 
        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            //put your code here...
        } ...
票数 0
EN

Stack Overflow用户

发布于 2014-01-05 01:14:14

为了补充Bugdayci的答案,一个完整的例子如下:

代码语言:javascript
复制
       ServiceConnection myConnection = new ServiceConnection() { 
            @Override
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                    ... your code that needs to execute on service connection       

            }


    @Override
    public void onServiceDisconnected(ComponentName name) {
        ... your code that needs to execute on service disconnection

    } 
        };

        Intent intent = new Intent(this, TheServiceClassName.class);
        bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

..。

如果末尾没有bindService,onServiceConnected()代码将不会执行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6896161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档