0

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

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

4

1 回答 1

0

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

Service绑定完成后,调用的onServiceConnected()方法。ServiceConnection由于此方法在主 (UI) 线程上调用,因此当代码在任何其他也在主 (UI) 线程上调用的方法(例如,onReceive().

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

  1. 绑定到Service
  2. 连接后Service,继续处理
于 2017-01-26T16:40:35.413 回答