ServiceConnection总是返回false

时间:2017-01-25 09:47:39

标签: android broadcastreceiver android-service android-notifications onserviceconnected

我正在尝试在MainActivity中绑定服务,绑定服务由在MainActivity中定义的方法updateTheNotification()中创建的intent绑定,如下所示:

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方法调用,该方法附加在通知上的按钮上。

1 个答案:

答案 0 :(得分:0)

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

Service绑定完成后,将调用onServiceConnected()的{​​{1}}方法。由于在main(UI)线程上调用此方法,因此在代码在主(UI)线程上也调用的任何其他方法中执行时无法调用它(例如,ServiceConnection

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

  1. 绑定到onReceive()
  2. 连接Service后,继续处理