我有一个服务,我正在尝试将一个活动绑定到它。问题是......运行后bindService(..)
,我在serviceconnection中设置的服务实例仍然为空,我不知道为什么。
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;
}
};
@Override
protected void onStart()
{
super.onStart();
//check start connection service
if(conn == null)
{
Intent serviceIntent = new Intent(this, ConnectionService.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
//connect to server
server.conn = conn;
//THIS STATEMENT FAILS: NULL REFERENCE, conn is Null here, and I have no idea why
conn.ConnectToServer(server);
server.StartReader();
}
是:服务在清单中定义。
是的:我可以从主活动启动服务(此代码驻留在由主活动启动的活动中,这是我需要绑定到服务的地方)我已经检查以确保服务确实启动了.. ..确实
根据我设法找到绑定服务的每个示例,这应该可以工作。谁能告诉我为什么不是?
编辑:添加服务代码定义
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
//some other code that has everything to do with what the service does, and nothing to do with how it should be started/run
}