【问题标题】:service instance still null after binding绑定后服务实例仍然为空
【发布时间】:2013-11-07 03:22:43
【问题描述】:

我有一个服务,我正在尝试将一个活动绑定到它。问题是……运行bindService(..)后,我在serviceconnection里面设置的服务实例还是null,不知道为什么。

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 Activity 启动服务(此代码驻留在由主要 Activity 启动的 Activity 中,这是我需要绑定到服务的地方)我已检查以确保服务确实执行开始......它确实

根据我设法找到绑定服务的每个示例,这应该可以工作。谁能告诉我为什么不行?

编辑:添加服务代码定义

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
}

【问题讨论】:

    标签: android service binding


    【解决方案1】:

    请检查清单中声明的​​服务。

    【讨论】:

      猜你喜欢
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      相关资源
      最近更新 更多