要与Service通信,bindService()和创建服务实例之间有什么不同?为什么需要使用bindService()与服务进行通信?我很困惑。
(1)
public class BLEService extends Service {
private static BLEService sService;
@Override
public void onCreate() {
super.onCreate();
sService = this;
}
public static BLEService getInstance() {
return sService;
}
}
public class HeartRateActivity extends Activity {
private BLEService mBLEService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBLEService = BLEService.getInstance();
}
}
(2)
public class BLEService extends Service {
private final IBinder mBinder = new LocalBinder();
private BLEService mBLEService;
public class LocalBinder extends Binder {
public MyleService getServerInstance() {
return MyleService.this;
}
}
}
public class HeartRateActivity extends Activity {
private BLEService mBLEService;
private boolean mBounded;
@Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, BLEService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mBLEService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mBLEService = mLocalBinder.getServerInstance();
}
};
}
由于
编辑:在服务的onCreate()中删除新运算符
答案 0 :(得分:0)
您将不使用new
关键字通过其构造函数实例化Service对象。服务旨在成为一个长期运行的进程,不一定与要访问它的活动的生命周期相关联。因此,服务是您使用Intent向Android发送的信号,您希望以与使用Intent对象发出信号表示您希望启动新活动相同的方式运行它们。
使用.bindService()
您可以向Android发出要附加到正在运行的服务的信号(并且如果它尚未运行则隐式启动该服务)。绑定后,您可以通过它可用的任何接口与服务进行通信。