当我切换活动时,我的BLE设备断开连接

时间:2016-05-11 09:14:20

标签: android bluetooth bluetooth-lowenergy gatt

当我从主屏幕切换到另一个活动时,我的BLE设备断开连接。这是我的主要活动:

public class MainActivity extends FragmentActivity implements OnDataReceivedListener, OnStateChangedListener, PopupMenu.OnMenuItemClickListener, WorkoutTimerInterface, WorkOutOverDialogInterface {


FlipApi flipApi;
CalcData calcData;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new WorkInBack().execute();


}

@Override
public void onHeartRateReceived(int hr) {

}


@Override
public void onStepsReceived(int steps) {

}


@Override
public void onBatteryReceived(int bae) {
}

@Override
public void onStateChanged(int state) {

}

@Override
public boolean onMenuItemClick(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.item_workout:
            Intent intent1 = new Intent(MainActivity.this, WorkOutList.class);
            MainActivity.this.startActivity(intent1);
            return true;

        default:
            return false;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    flipApi.disconnect();
    Log.d("On destroy","");
}

class WorkInBack extends AsyncTask<Context, Void, Void> {

    @Override
    protected Void doInBackground(Context... params) {

        database_steps = new DatabaseHandler(MainActivity.this, "steps_table");
        database_workout = new DatabaseHandler(MainActivity.this, "flip_table");
        flipApi = new FlipApi(MainActivity.this);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        flipApi.initApi();
        flipApi.setOnDataReceivedListener(MainActivity.this);
        flipApi.setOnStateChangeListener(MainActivity.this);

        logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flipApi.startScan();
            }
        });
    }
}

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences.Editor editor = workout_session.edit();
    editor.putInt("last_steps", steps_total);
    editor.putFloat("distance", distance);
    editor.apply();
    database_workout.close();
}

@Override
public void onBackPressed() {
    if (exit == 1) {
        exit = 0;
        finish();
    } else {
        Snackbar.make(x, "Press Back Again to Exit", Snackbar.LENGTH_SHORT).show();
        exit = 1;
    }
}

所以,我有一个弹出菜单,可以将我重定向到另一个活动。当我点击这个时,我从Bluetooth Gatt那里得到一个日志,说它关闭了。我也查看了我的API,发现没有问题。这是我的API,以防它有用:

public class FlipApi {

Intent iBluetoothLeService;
static BluetoothDevice mBluetoothDevice;
BluetoothAdapter mBluetoothAdapter;
private ProgressDialog mProgressDialog;
float x_p=0,x_e=60,P_p=1,P_e=1,Q=0.01f,RM=0.5f,K=0;

Context activitycontext ;
private OnDataReceivedListener onDataReceivedListener;
private OnStateChangedListener onStateChangedListener;

public static final int STATE_CONNECTED = 0x45;
public static final int STATE_DISCONNECTED = 0x46;

boolean isBond = false;

public FlipApi(Context context)
{
    this.activitycontext = context;
}
ScanCallback mLeScanCallback;
public void initApi()
{
    mProgressDialog = new ProgressDialog(activitycontext);
    mProgressDialog.setCanceledOnTouchOutside(false);
    mProgressDialog.setMessage("finding device");

    IntentFilter intentFilter= new IntentFilter();
    intentFilter.addAction("com.flip.data");
    activitycontext.registerReceiver(bluetoothDataReceiver,intentFilter);


    final BluetoothManager bluetoothManager =
            (BluetoothManager) activitycontext.getSystemService(Context.BLUETOOTH_SERVICE);

    mBluetoothAdapter = bluetoothManager.getAdapter();

    if(mBluetoothAdapter==null) {
        Toast.makeText(activitycontext, "Bluetooth not found", Toast.LENGTH_LONG).show();
    }
    else if(!mBluetoothAdapter.isEnabled()){
        Intent enableBluetooth= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activitycontext.startActivity(enableBluetooth);
    }
    if(Build.VERSION.SDK_INT >=21) {
        mLeScanCallback =
                new ScanCallback() {
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onScanResult(int callbackType, ScanResult result) {
                        super.onScanResult(callbackType, result);


                        try {
                            if (result.getDevice().getName().contains("FLIP9") || result.getDevice().getName().contains("FLIP8")) {

                                mProgressDialog.dismiss();

                                mBluetoothDevice = result.getDevice();

                                iBluetoothLeService = new Intent(activitycontext, BluetoothLeService.class);

                                isBond = activitycontext.bindService(iBluetoothLeService, mServiceConnection, Context.BIND_AUTO_CREATE);


                                Log.d("flip", "device found");

                                Toast.makeText(activitycontext, result.getDevice().getName() + " found", Toast.LENGTH_SHORT).show();

                                mBluetoothAdapter.getBluetoothLeScanner().stopScan(mLeScanCallback);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    @Override
                    public void onScanFailed(int errorCode) {
                        super.onScanFailed(errorCode);

                    }

                };
    }
}

public void startScan()
{
    if(mBluetoothAdapter.isEnabled()) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(mLeScanCallback!=null) {
                mBluetoothAdapter.getBluetoothLeScanner().startScan(mLeScanCallback);
                mProgressDialog.show();
            }
        }
        else
        {
           // mBluetoothAdapter.startLeScan(mLeScanCallbackFucksSamsung);
            if(mBluetoothDevice == null) {
                mBluetoothAdapter.startLeScan(mLeScanCallbackFucksSamsung);
                mProgressDialog.show();
            }
            else
            {
                iBluetoothLeService = new Intent(activitycontext,BluetoothLeService.class);
                isBond = activitycontext.bindService(iBluetoothLeService, mServiceConnection, Context.BIND_AUTO_CREATE);
            }
        }

    }
    else
    {
        Toast.makeText(activitycontext, "Please switch on bluetooth", Toast.LENGTH_LONG).show();
    }
}

public void setOnDataReceivedListener(OnDataReceivedListener onDataREceivedListener)
{
    this.onDataReceivedListener = onDataREceivedListener;
}

public void setOnStateChangeListener(OnStateChangedListener onStateChangeListener)
{
    this.onStateChangedListener = onStateChangeListener;
}

private final BroadcastReceiver  bluetoothDataReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int id = intent.getIntExtra("id",-1);
        final int value = intent.getIntExtra("value",-1);
        Log.d("flip","id = "+id +" value = "+value);
        switch(id)
        {
            case 0:
                x_p = x_e;
                P_p = P_e + Q;

                K = P_p/(P_p+RM);
                x_e = x_p + K*(value - x_p);
                P_e = (1-K)*P_p;
                int k_value = (int) x_e;
                if(onDataReceivedListener!=null)
                onDataReceivedListener.onHeartRateReceived(k_value);

                break;
            case 1:
                if(onDataReceivedListener!=null)
                onDataReceivedListener.onStepsReceived(value);
                break;
            case 2:
                if(onStateChangedListener!=null)
                onStateChangedListener.onStateChanged(STATE_CONNECTED);
                Toast.makeText(activitycontext,"Device Connected",Toast.LENGTH_SHORT).show();
                break;
            case 3:
                if(onStateChangedListener!=null)
                onStateChangedListener.onStateChanged(STATE_DISCONNECTED);
                Toast.makeText(activitycontext,"Device Disconnected",Toast.LENGTH_SHORT).show();
                iBluetoothLeService = null;
                activitycontext.unbindService(mServiceConnection);
                break;
            case 4:
                if(onDataReceivedListener!=null)
                onDataReceivedListener.onBatteryReceived(value);
                break;
        }
    }
};

private BluetoothAdapter.LeScanCallback mLeScanCallbackFucksSamsung= new BluetoothAdapter.LeScanCallback(){
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
    {

        try {
            if (device.getName().contains("FLIP9") || device.getName().contains("FLIP8")){

                mProgressDialog.dismiss();

                mBluetoothDevice = device;

                iBluetoothLeService = new Intent(activitycontext,BluetoothLeService.class);

                isBond = activitycontext.bindService(iBluetoothLeService, mServiceConnection, Context.BIND_AUTO_CREATE);



                Log.d("flip", "device found");

                mBluetoothAdapter.stopLeScan(mLeScanCallbackFucksSamsung);
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
};



private final ServiceConnection mServiceConnection = new ServiceConnection() {

    BluetoothLeService mBluetoothLeService;
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        mBluetoothLeService.initialize();
        mBluetoothLeService.connect(mBluetoothDevice.getAddress());

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};

public void disconnect()
{
    if(mServiceConnection!=null && isBond)
    {
        activitycontext.unbindService(mServiceConnection);

    }

    activitycontext.unregisterReceiver(bluetoothDataReceiver);
}

1 个答案:

答案 0 :(得分:0)

这是因为当活动被破坏时你与api断开连接。

@Override
protected void onDestroy() {
    super.onDestroy();
    flipApi.disconnect();
    Log.d("On destroy","");
}

如果您希望您的api适用于所有活动,您可以将其移至应用程序类

请参阅Why extend an Application class?