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

Android 从UI线程启动服务时断开连接,android,bluetooth-lowenergy,Android,Bluetooth Lowenergy,当我尝试从UI线程绑定服务时,我的BluetoothLeService在一段时间后变为null。mBlutoothLeService设置正确,但在执行多个gattUpdateReceiver后,它变为null private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override

当我尝试从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;
    }


};
我尝试使用处理程序(新处理程序(getActivity().getMainLooper())绑定服务,但mBluetoothLeService仍然变为null。
但当我在新片段的OnCreate()中启动绑定服务时,它可以正常工作。这与UI线程有关吗?

您可能无法使用
getActivity()
以可运行的方式获取当前活动---

所以,我们的想法是使用
onCreate()
上的绑定服务

但是,您可以在asyntask中使用---

class MyClass扩展了异步任务{
私人活动;
公共MyClass(活动){
当前活动=活动;
}
@凌驾
公开募捐{
if(device!=null&&device.getName()!=null){
Intent gattServiceIntent=新的Intent(currentActivity,BluetoothLeService.class);
getActivity().bindService(gattServiceIntent,
mServiceConnection,Context.BIND(自动创建);
}
});
}

您应该仅从UI线程与服务通信
@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);

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

       }
    });
}