Android BLE前台服务

时间:2017-02-11 13:22:18

标签: android bluetooth bluetooth-lowenergy foreground-service

我在使用前台服务的BLE通信时遇到了一些麻烦。 虽然服务上的逻辑工作正常,但如果活动是开放的,每当蓝牙设备在范围内时,我的服务就会做它必须做的事情。但是在我关闭或暂停活动之后,我的服务只运行一次,它似乎忽略了扫描回调并且没有做任何事情。

预期的行为应该是即使主活动关闭,服务也应该找到并执行相关的逻辑。

public class DeviceControlService extends Service implements  BluetoothAdapter.LeScanCallback{
private String TAG = "In Service --> ";
private BluetoothAdapter mBluetoothAdapter;                                         //BluetoothAdapter represents the radio in the Smartphone
private boolean mScanning;                                                          //Keep track of whether there is a scan in progress
private static final long SCAN_PERIOD = 100000;                                      //Length of time in milliseconds to scan for BLE devices

private String wantedDevice = "00:1E:C0:29:2A:BE";
private boolean found = false;
InServiceControl deviceControl;
private boolean switchStatus = true;
BluetoothManager bluetoothManager;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();

private States state = IDLE;
private PendingIntent pendingIntent;
private  BluetoothAdapter.LeScanCallback mLeScanCallback;

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    DeviceControlService getService() {
        // Return this instance of LocalService so clients can call public methods
        return DeviceControlService.this;
    }
}


@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public void stopThread(){
    Log.d(TAG, "thread stoped");
    stopScanning();
    switchStatus = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
    Log.d(TAG, "On start");
    return START_STICKY;
}

@Override
public void onCreate(){
    state = INIT;
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    Notification notification = new Notification.Builder(this)
            .setContentTitle("MBO")
            .setContentText("Bluetooth is running.")
            .setSmallIcon(R.drawable.tooth)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(101, notification);
    adapterInit();
    scanLeDevice();
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(switchStatus)
                states();
        }
    }).start();
}





@Override
public void onDestroy() {
    deviceControl = null;
    bluetoothManager = null;
    mBluetoothAdapter = null;
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}

public void adapterInit(){
    Log.d(TAG, "in adapter init");
    bluetoothManager = (android.bluetooth.BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); //Get the BluetoothManager
    mBluetoothAdapter = bluetoothManager.getAdapter();
    deviceControl = new InServiceControl(mBluetoothAdapter, this);

}

public void states(){

    switch(state){
        case IDLE:
            break;
        case INIT:
            switchStatus = true;
            Log.d(TAG, "init");
            if(mBluetoothAdapter == null){
                adapterInit();
            }
            state = PROCESSING;
            break;
        case PROCESSING:
            if(!mScanning){
                scanLeDevice();
            }else{
                try {
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            break;

        case DONE:
            Log.d(TAG, "done");

            state = PROCESSING;
            break;
        default:
            break;

    }
}

// ----------------------------------------------------------------------------------------------------------------
// Scan for BLE device for SCAN_PERIOD milliseconds.
// The mLeScanCallback method is called each time a device is found during the scan
private void scanLeDevice() {
    Log.d(TAG, "Entered into scanning");

    if(!mScanning){
        Log.d(TAG, "started Scanning");
        mBluetoothAdapter.startLeScan(this);
        mScanning = true;
    }

}

private void stopScanning(){
    Log.d(TAG, "scanning stoped");
    if(mScanning) {
        mBluetoothAdapter.stopLeScan(this);
        mScanning = false;
    }
}


public void autoConnect(BluetoothDevice device){
                                                                      //Stop the scan in progress
    deviceControl.init(device.getName(), device.getAddress());
    state = DONE;

}


    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { //Android calls method with Bluetooth device advertising information

        if(device.getAddress().equals(wantedDevice)){
            stopScanning();
            autoConnect(device);
            Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
        }

        Log.d(TAG, "Found BLE Device: " + device.getAddress()  ); //Debug information to log the devices as they are found
    }

由于某些原因我错过了android是否可能忽略了扫描回调?

提前致谢

0 个答案:

没有答案