I want to bind service with multiple activities so I've written an Application class to managed this goal:
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;
}
};
}
And to access this class in Activity I'm using for example:
BluetoothController.getInstance().startService();
But I have an error: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gmail.krakow.michalt.myecg.BluetoothController.startService()' on a null object reference. How can it be solved?