使用多个活动绑定服务

时间:2017-09-29 12:37:04

标签: java android android-service

我想将服务绑定到多个活动,因此我编写了一个Application类来管理这个目标:

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;
        }
    };
}

要在活动I中访问此类,例如:

BluetoothController.getInstance().startService();

但是我有一个错误:java.lang.NullPointerException:尝试调用虚方法' void com.gmail.krakow.michalt.myecg.BluetoothController.startService()'在null对象引用上。 怎么解决?

1 个答案:

答案 0 :(得分:-1)

public static synchronized BluetoothController getInstance() {
    return mInstance = new BluetoothController();
}
相关问题