从UI线程启动时,服务断开连接

时间:2014-03-22 06:12:13

标签: android bluetooth-lowenergy

当我尝试从UI线程绑定服务时,我的BluetoothLeService在一段时间后变为null。 mBlutoothLeService设置正确,但在执行多个gattUpdateReceiver后,它变为null。

private BluetoothAdapter.LeScanCallback mLeScanCallback =
                               new   BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (device != null && device.getName() != null) {
                    Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
                    getActivity().bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

                }
        });
    }
};


private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName,
            IBinder service) {
        Log.e(TAG, "service connected");

        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                .getService();

        mBluetoothLeService.connect(mDeviceAddress);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.e(TAG, "service disconnected");
        mBluetoothLeService = null;
    }


};

我尝试使用handler(new Handler(getActivity()。getMainLooper())绑定服务但仍然mBluetoothLeService变为null。 但是当我在新片段的OnCreate()中启动绑定服务时,它没有任何问题。是否与UI线程有关?

1 个答案:

答案 0 :(得分:0)

您可能无法使用getActivity()使用此代码在Runnable ---

中获取当前活动
@Override
public void run() {

if (device != null && device.getName() != null) {
   Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
   getActivity().bindService(gattServiceIntent, 
   mServiceConnection, Context.BIND_AUTO_CREATE);

   }
});

因此,想法是在onCreate()使用绑定服务。

但是,您可以使用---

获取asyntask中的活动
class MyClass extends AsyncTask<String, String, String> {

        private Activity currentActivity;

        public MyClass(Activity activity) {
            currentActivity = activity;
        }

@Override
    public void run() {

    if (device != null && device.getName() != null) {
       Intent gattServiceIntent = new Intent(currentActivity, BluetoothLeService.class);
       getActivity().bindService(gattServiceIntent, 
       mServiceConnection, Context.BIND_AUTO_CREATE);

       }
    });
}