为什么我的有界android服务是null?

时间:2013-08-25 11:58:02

标签: java android service binding

我有以下代码:

public void refreshWidget() {
    doBindService();
     mBoundService.loadState();
    doUnbindService();
}


private static ServiceConnection mAppWidgetServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service. Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
        mBoundService = ((AppWidgetService.LocalBinder) service)
                .getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        // Because it is running in our same process, we should never
        // see this happen.
        mBoundService = null;
    }
};

static void doBindService() {
    // Establish a connection with the service. We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    if (!mIsBound) {
        // mContext.startService(new Intent(mContext,
        // AppWidgetService.class));
        mContext.bindService(new Intent(mContext,
                AppWidgetService.class),
                mAppWidgetServiceConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
}

这一行mBoundService==null中的mBoundService.loadState();怎么可能?

我错过了什么?

1 个答案:

答案 0 :(得分:0)

你不能立即在 doBindService(); 之后立即调用 mBoundService.loadState(); ,因为此时服务没有限制。

在回调 onServiceConnected 之后调用 mBoundService.loadState();