不可能解开服务

时间:2016-03-12 18:24:38

标签: android

我启动我的app,调用start,执行bind服务并触发onServiceConnected。一切都很好。

但是...

当我按回来时,onStop被调用,我的绑定var是真的,但是从未调用onServiceDisconnected ......

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onStart()
{
    Log.e("START", "START");

    super.onStart();

    // Bind to LocalService
    Intent intent = new Intent(this, LocationService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop()
{
    Log.e("STOP", "STOP");

    super.onStop();

    // Unbind from the service
    if (mBound)
    {
        this.unbindService(mConnection);
        mBound = false;
    }
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection()
{
    @Override
    public void onServiceConnected(ComponentName className, IBinder service)
    {
        Log.e("ON SERVICE START", "ON SERVICE START");

        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocationService.LocationBinder binder = (LocationService.LocationBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0)
    {
        Log.e("ON SERVICE END", "ON SERVICE END");

        mBound = false;
    }
};

我的服务

// Binder given to clients
private final IBinder mBinder = new LocationBinder();

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocationBinder extends Binder
{
    public LocationService getService()
    {
        // Return this instance of LocationService so clients can call public methods
        return LocationService.this;
    }
}

@Override
public IBinder onBind(final Intent intent)
{
    Log.e("onBind", "onBind onBind onBind onBind onBind onBind");

    return mBinder;
}

/** method for clients */
public int getRandomNumber()
{
    return new Random().nextInt(100);
}

1 个答案:

答案 0 :(得分:1)

bindService()的每次通话都应与对unbindService()的通话配对。如果绑定工作与否,实际上并不重要。重点是让Android知道您不再希望连接处于活动状态。 Android将负责确定连接当前是否已绑定并处于活动状态并执行相应操作的详细信息。

底线是你不应该在这里有条件地调用unbindService()。只需在onStop()中调用它,并使用在onStart()中调用bindService()时使用的相同ServiceConnection。