开发者

Android binding to Service

I'm binding to a Service, using context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);. This method returns true. But I don't get connected. Some code:

// Snippet from method, that connects to service:
boolean result = context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "is connected: " + connected);
return result;
}

// Connection:
private ServiceConnection connection = new ServiceConnection() {

        public voi开发者_开发知识库d onServiceConnected(ComponentName name, IBinder service) {
            parser = Parser.Stub.asInterface(service);
            Log.d(TAG, "Connected to service...");
            connected = true;
        }

        public void onServiceDisconnected(ComponentName name) {
            parser = null;
            Log.d(TAG, "Disconnected from service...");
            connected = false;
        }

    };

Eventually, I don't get into onServiceConnected method: no messages in logcat except for D/FrameworkBridge( 926): is connected: false. Any ideas?

UPD: I commented immediate call to service method (that was throwing NPE) after I connect to it, and everything worked well: the service is started and binded to. Seems like the connection is created in a separate thread, or so. Is there any way I can make my class wait, util the connection is actually established?


I ran in to the same issue and found out that I had to call startService as well to get it working: http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)

This is what my code looks like:

startService(new Intent(MainActivity.this, WeatherService.class));

bindService(new Intent(MainActivity.this, 
                WeatherService.class), mConnection, Context.BIND_AUTO_CREATE);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜