服务:启动绑定服务

时间:2017-11-08 16:06:15

标签: android android-service

我对绑定服务感到困惑。我在这篇文章中读到了Can anybody explain what is difference between unbound and bound service in android,并在此基础上我正在尝试一个样本。我创建了一个服务并将其绑定到我的活动,如下所示

public class MyService extends Service {
private static final String TAG = "MyService";
MyBinder mMyBinder = new MyBinder();

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand: ");
    // start long running operation
    return super.onStartCommand(intent, flags, startId);
}

@Override
public boolean onUnbind(Intent intent) {
    Log.d(TAG, "onUnbind: ");
    return super.onUnbind(intent);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind: ");
    return mMyBinder;
}

public class MyBinder extends Binder {
    public MyService getService(){
        return MyService.this;
    }
}
}

活动

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
MyService.MyBinder mMyBinder;
private Connect mConn;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, MyService.class);
    mConn = new Connect();
    bindService(intent, mConn, BIND_AUTO_CREATE);
}


public class Connect implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d(TAG, "onServiceConnected: ");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(TAG, "onServiceDisconnected: ");
    }
  }
 }

调用bindService(intent, mConn, BIND_AUTO_CREATE);

时,不会调用服务'onStartCommand'

我应该在绑定后调用startService吗?绑定不会启动服务?

如果我已经有一个使用startService启动并且正在运行的服务,并且我在其他一些活动中绑定了相同的服务,那么如果活动超出范围会发生什么?

0 个答案:

没有答案