绑定后,服务实例仍为null

时间:2013-11-07 03:22:44

标签: android service binding

我有一项服务,我正在尝试将活动绑定到它。问题是......在运行bindService(..)之后,我在服务连接中设置的服务实例仍为空,我不知道原因。

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();
}

是:服务在清单中定义。

是:我可以从MAIN活动启动服务(此代码驻留在主活动启动的活动中,这是我需要绑定到服务的地方)我已经检查以确保服务实际上是开始....它确实

根据我设法找到绑定服务的每个例子,这应该是有效的。谁能告诉我为什么不呢?

修改:添加服务代码定义

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
}

1 个答案:

答案 0 :(得分:0)

请检查Manifest中声明的服务。