首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ServiceConnection总是将错误返回给我

ServiceConnection总是将错误返回给我
EN

Stack Overflow用户
提问于 2017-01-25 09:47:39
回答 1查看 167关注 0票数 0

我试图在MainActivity中绑定服务,绑定服务受在updateTheNotification()中定义的方法MainActivity中创建的意图的约束,如下所示:

代码语言:javascript
复制
public void updateTheNotification()
    {

        Intent intentz = new Intent(context.getApplicationContext(), NotificationService.class);
        context.getApplicationContext().bindService(intentz, mConnection, Context.BIND_ABOVE_CLIENT);
        if (mBound) {
            // Call a method from the LocalService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            mService.changeTheUI(true);
            Toast.makeText(this, "Service triggered", Toast.LENGTH_LONG).show();
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            NotificationService.LocalBinder binder = (NotificationService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

updateTheNotification()由附加在通知按钮上的广播接收器onReceive方法调用。

EN

回答 1

Stack Overflow用户

发布于 2017-01-26 16:40:35

方法bindService()是异步的。这意味着该方法将立即返回,即使Service尚未绑定。

Service绑定完成后,调用ServiceConnectiononServiceConnected()方法。由于此方法是在main (UI)线程上调用的,所以当代码在主(UI)线程上调用的任何其他方法(例如,onReceive() )中执行时,不能调用该方法。

您需要将您的处理分为两部分:

  1. 绑定到Service
  2. 连接Service后,继续处理
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41848256

复制
相关文章

相似问题

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