0
我想绑定多个活动服务,所以我写了一个应用程序类来管理这个目标:与多个活动绑定服务
public class BluetoothController extends Application {
private static BluetoothController mInstance;
private ClientBluetoothService mService;
protected boolean mBound = false;
public static synchronized BluetoothController getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
}
public void startService(){
//start your service
Intent intent = new Intent(this, ClientBluetoothService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopService(){
//stop service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
public ClientBluetoothService getService(){
return mService;
}
public boolean isBound() {
return mBound;
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
ClientBluetoothService.LocalBinder binder = (ClientBluetoothService.LocalBinder) service;
mService = binder.getSerivce();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
并访问这个类在我使用例如活动:
BluetoothController.getInstance().startService();
但是我有一个错误:显示java.lang.NullPointerException:尝试调用虚拟方法“无效com.gmail.krakow.michalt.myecg.BluetoothController.startService()”上的空对象引用。 如何解决?
另外 - 根本没有必要这样做。如果你想将多个活动绑定到一个服务,只需在每个中调用bindService。或者把它放到你的活动的通用基类中。将它应用到应用程序中是没有意义的 –
您打算如何使用'BluetoothController',调用'isBound()'后跟'getService()',然后用意图手动绑定? – samosaris
这不是最好的主意。如果遵循@GabeSechan给出的指示,它运作良好。 – michalt38