【问题标题】:ServiceConnection returns me false alwaysServiceConnection 总是返回 false
【发布时间】:2017-01-25 09:47:39
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 是的,这就是为什么我放弃了 binder 的想法,因为我也想更新 UI。所以我所做的就是让服务独立于 MainActivity,在我的情况下,我在单独的服务中处理媒体播放器,并使用意图过滤器操作进行调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2021-11-05
    • 2018-11-05
    • 2019-05-06
    • 2017-04-29
    • 2013-04-30
    • 2015-01-20
    相关资源
    最近更新 更多