Example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

List of usage examples for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Prototype

String ACTION_STATE_CHANGED

To view the source code for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Click Source Link

Document

Broadcast Action: The state of the local Bluetooth adapter has been changed.

Usage

From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java

private static IntentFilter makeIntentFilter() {
    IntentFilter intentFilter = new IntentFilter();

    intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    intentFilter.addAction(ACTION_KEYBOARD_UPDATE_CONFIRMED);
    intentFilter.addAction(ACTION_KEYBOARD_UPDATE_POSTPONED);

    return intentFilter;
}

From source file:com.github.akinaru.hcidebugger.activity.HciDebuggerActivity.java

public void onResume() {
    super.onResume();
    //register bluetooth receiver
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

    registerReceiver(mBroadcastReceiver, intentFilter);
}

From source file:com.improvelectronics.sync.android.SyncStreamingService.java

private void setupIntentFilter() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(mMessageReceiver, intentFilter);
}

From source file:com.snt.bt.recon.activities.MainActivity.java

private boolean startScan() {
    //Toast.makeText(getApplicationContext(), "Start scan", Toast.LENGTH_SHORT).show();
    logDebug("Activity", "######################## startScan ########################");

    final boolean mIsBluetoothOn = mBluetoothUtils.isBluetoothOn();
    final boolean mIsBluetoothLePresent = mBluetoothUtils.isBluetoothLeSupported();
    //enable bt adapter
    mBluetoothUtils.getBluetoothAdapter().enable();
    //mBluetoothUtils.askUserToEnableBluetoothIfNeeded();
    registerReceiver(BluetoothAdapterReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

    //BLE//from  w  w w  .  ja  v a2  s. com
    mLeDeviceStore.clear();
    mLeDeviceListAdapter = new LeDeviceListAdapter(this, mLeDeviceStore.getDeviceCursor());
    mList1.setAdapter(mLeDeviceListAdapter);

    //BC
    mBcDeviceListAdapter = new BcDeviceListAdapter(this, mBcDeviceList); //BC Addon
    mList2.setAdapter(mBcDeviceListAdapter);
    mBcDeviceListAdapter.clear();

    if (mIsBluetoothOn && mIsBluetoothLePresent && gpsStatusCheck()) {

        //sessionid
        sessionId = UUID.randomUUID();

        //save trip to database
        db.addTrip(new Trip(sessionId, telephonyManager.getDeviceId(),
                new TransportMode(this).getTransportMode(), getDateTime(), "0",
                BuildConfig.VERSION_CODE + " (" + BuildConfig.VERSION_NAME + ")", "no"));

        //BLE
        mLeScanner.scanLeDevice(-1, true);

        //BC
        // Register receiver to get message from BtServiceReceiver
        registerReceiver(BtScanServiceReceiver, new IntentFilter(BcScanService.ACTION_START_SCAN));
        Intent newIntent = new Intent(this, BcScanService.class);
        newIntent.setAction(BcScanService.ACTION_START_SCAN);
        newIntent.putExtra(BcScanService.EXTRA_SID, sessionId.toString());
        startService(newIntent);
        BcScanService.IS_SERVICE_RUNNING = true;

        //reset location id in case old are still stored
        locationId = null;
        BcScanService.locationId = null;

        Toast.makeText(getApplicationContext(), "Starting BC Service...", Toast.LENGTH_SHORT).show();

        invalidateOptionsMenu();

        return true;
    }
    return false;

}

From source file:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java

/**
 * Handles intents ACTION_CONNECTION_STATE_CHANGED, ACTION_STATE_CHANGED,
 * ACTION_BOND_STATE_CHANGED, ACTION_KEYBOARD_UPDATE_CONFIRMED.
 * <p/>/*from   w w  w .j  a v a2  s .  co m*/
 * [ACTION_STATE_CHANGED]
 * This action is used to keep track of ON/OFF state change on the system Bluetooth adapter.
 * The
 * purpose is to synchronize the local Bluetooth connectivity with system Bluetooth state.
 * <p/>
 * [ACTION_CONNECTION_STATE_CHANGED]
 * This action is used to keep track of the connection change on the target device. The purpose
 * is to synchronize the connection cycles of the local GATT connection and the system
 * Bluetooth
 * connection.
 * <p/>
 * [ACTION_BOND_STATE_CHANGED]
 * This action is used to keep track of the bond state change on the target device. The purpose
 * is to the connection cycles of the local GATT connection and the system Bluetooth
 * connection.
 * <p/>
 * [ACTION_KEYBOARD_UPDATE_CONFIRMED]
 * This action is used to receive the update confirmation from the user. The purpose is to
 * trigger DFU process.
 */
private void onHandleIntent(Context context, Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onHandleIntent: Received action: " + action);

    if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {

        if (!isBluetoothEnabled()) {
            Log.w(TAG, "onHandleIntent: Bluetooth connectivity not enabled");
            return;
        }

        // Match the connected device with the default keyboard name.
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceConnectionState = extras.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE);

        Log.d(TAG, "onHandleIntent: " + device.getName() + " [" + device.getAddress() + "] change to state: "
                + deviceConnectionState);

        // Match the name of the target keyboard.
        if (!isTargetKeyboard(device))
            return;

        if (deviceConnectionState == BluetoothAdapter.STATE_CONNECTED) {
            // Prevent the second keyboard from using the service.
            if (isUpdateServiceInUse())
                return;

            obtainKeyboardInfo(device.getName(), device.getAddress());

            if (mDfuStatus != DFU_STATE_INFO_READY) {
                Log.w(TAG, "onHandleIntent: DFU preparation failed");
                changeDfuStatus(DFU_STATE_OBTAIN_INFO_ERROR);
                return;
            }

            showUpdateNotification();
        } else if (deviceConnectionState == BluetoothAdapter.STATE_DISCONNECTING) {
            handleGattDisconnection();
        }

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        if (adapterState == BluetoothAdapter.STATE_ON) {
            if (!isBluetoothEnabled())
                enableBluetoothConnectivity();
        } else if (adapterState == BluetoothAdapter.STATE_TURNING_OFF) {
            // Terminate update process and disable Bluetooth connectivity.
            disableBluetoothConnectivity();

            // Since BluetoothAdapter has been disabled, the callback of disconnection would not
            // be called. Therefore a separate clean-up of GATT connection is need.
            cleanUpGattConnection();
        }

    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceBondState = extras.getInt(BluetoothDevice.EXTRA_BOND_STATE);

        Log.d(TAG, "onHandleIntent: state change on device " + device.getName() + " [" + device.getAddress()
                + "], bond state: " + deviceBondState);

        if (!isTargetKeyboard(device))
            return;

        if (deviceBondState == BluetoothDevice.BOND_NONE) {
            handleGattDisconnection();
        }

    } else if (ACTION_KEYBOARD_UPDATE_CONFIRMED.equals(action)) {
        dismissUpdateNotification();

        if (mDfuStatus != DFU_STATE_INFO_READY || mDfuStatus == DFU_STATE_UPDATING) {
            Log.w(TAG, "onHandleIntent: DFP preparation not ready or DFU is in progress. ");
            changeDfuStatus(DFU_STATE_UPDATE_ABORTED);
            return;
        }

        String keyboardName = intent.getStringExtra(EXTRA_KEYBOARD_NAME);
        String keyboardAddress = intent.getStringExtra(EXTRA_KEYBOARD_ADDRESS);
        if (!mKeyboardName.equals(keyboardName) || !mKeyboardAddress.equals(keyboardAddress)) {
            Log.w(TAG, "onHandleIntent: No DFU service associated with " + keyboardName + " [" + keyboardAddress
                    + "]");
            return;
        }

        Log.d(TAG, "onHandleIntent: Start update process on " + keyboardName + " [" + keyboardAddress + "]");
        changeDfuStatus(DFU_STATE_SWITCHING_TO_DFU_MODE);

    } else if (ACTION_KEYBOARD_UPDATE_POSTPONED.equals(action)) {
        dismissUpdateNotification();
        // TODO(mcchou): Update the preference when the Settings keyboard entry is available.
    }
}

From source file:saphion.services.ForegroundService.java

@SuppressWarnings("deprecation")
@Override// ww  w . j a v a2 s  .c  o m
public void onCreate() {

    mPref = ForegroundService.this.getSharedPreferences(PREF_NAME, MODE_MULTI_PROCESS);

    // receive ACTION_BATTERY_CHANGED.
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_BATTERY_CHANGED);
    filter.addAction(Intent.ACTION_POWER_CONNECTED);
    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intents.MYBAT_INTENT);
    filter.addAction(Intents.TORCH_ON);
    filter.addAction(Intents.TORCH_OFF);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
        filter.addAction(Intents.SWITCHER_INTENT);
        filter.addAction(Intents.SWITCHER_NOTI);
        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
    }
    registerReceiver(mBroadcastReceiver, filter);

    readbattery();

    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (!mPref.getBoolean(PreferenceHelper.NOTIFICATION_ENABLE, true)) {
        mNM.cancelAll();// .notify(id, notification);

    }
    try {
        mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature);
        return;
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
    try {
        mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!");
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.NearbyActivity.java

private void findBluetooth() {
    if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        Intent bt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(bt, RESULT_BT_ENABLE);
        return;/*  w w  w  .  j  a  v a 2s  .c o  m*/
    }

    // Create a BroadcastReceiver for ACTION_FOUND
    final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

    final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(final Context context, final Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                new Thread() {
                    public void run() {
                        BluetoothBeacon.OnDiscovered discovered = new BluetoothBeacon.OnDiscovered() {
                            @Override
                            public void onDiscovered(final byte[] data) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            JSONObject obj = new JSONObject(new String(data));
                                            mNearbyList.add(
                                                    new NearbyItem(NearbyItem.Type.FEED, obj.getString("name"),
                                                            Uri.parse(obj.getString("dynuri")), null));
                                            mAdapter.notifyDataSetChanged();
                                        } catch (JSONException e) {
                                            Log.e(TAG, "Error getting group info over bluetooth", e);
                                        }
                                    }
                                });
                            }
                        };
                        // Get the BluetoothDevice object from the Intent
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        BluetoothBeacon.discover(NearbyActivity.this, device, discovered);
                    };
                }.start();
            }
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                unregisterReceiver(this);
            }
        }
    };

    registerReceiver(receiver, filter); // Don't forget to unregister during
                                        // onDestroy
    BluetoothAdapter.getDefaultAdapter().startDiscovery();
    Toast.makeText(this, "Scanning Bluetooth...", 500).show();
}

From source file:ibme.sleepap.recording.SignalsRecorder.java

/**
 * Called when the activity is first created. onStart() is called
 * immediately afterwards./*  w  ww  .  j  ava2  s.  c o m*/
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signals_recorder);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Log both handled and unhandled issues.
    if (sharedPreferences.getBoolean(Constants.PREF_WRITE_LOG, Constants.DEFAULT_WRITE_LOG)) {
        String bugDirPath = Environment.getExternalStorageDirectory().toString() + "/"
                + getString(R.string.app_name) + "/" + Constants.FILENAME_LOG_DIRECTORY;
        File bugDir = new File(bugDirPath);
        if (!bugDir.exists()) {
            bugDir.mkdirs();
        }
        String handledFileName = bugDirPath + "/logcat" + System.currentTimeMillis() + ".trace";
        String unhandledFileName = bugDirPath + "/unhandled" + System.currentTimeMillis() + ".trace";
        // Log any warning or higher, and write it to handledFileName.
        String[] cmd = new String[] { "logcat", "-f", handledFileName, "*:W" };
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e1) {
            Log.e(Constants.CODE_APP_TAG, "Error creating bug files", e1);
        }
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(unhandledFileName));
    }

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    extras = getIntent().getBundleExtra(Constants.EXTRA_RECORDING_SETTINGS);
    actigraphyEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_ACTIGRAPHY, false);
    audioEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_AUDIO, false);
    ppgEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_PPG, false);
    dateTimeString = DateFormat.format(Constants.PARAM_DATE_FORMAT, System.currentTimeMillis()).toString();
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    String appDirPath = Environment.getExternalStorageDirectory().toString() + "/"
            + getString(R.string.app_name);
    filesDirPath = appDirPath + "/" + dateTimeString + "/";
    lastAccelerometerRecordedTime = 0;
    lastPositionChangeTime = System.currentTimeMillis();
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.CODE_APP_TAG);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    actigraphyQueue = new LinkedList<Double>();
    positionDisplay = (TextView) findViewById(R.id.position);
    recordingSign = (ImageView) findViewById(R.id.recordingSign);

    for (int i = 0; i < 5; ++i) {
        totalPositionTime[i] = 0;
    }

    // Battery check receiver.
    registerReceiver(this.batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    // Button to stop the recording.
    Button stopButton = (Button) findViewById(R.id.buttonStop);
    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewNext) {
            stopRecording();
        }
    });

    // Button to reconnect the bluetooth.
    reconnectButton = (Button) findViewById(R.id.reconnectButton);
    reconnectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewNext) {
            String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS,
                    Constants.DEFAULT_MAC_ADDRESS);
            noninManager = null;
            noninManager = new NoninManager(getApplicationContext(), bluetoothAdapter, macAddress,
                    new PpgHandler(SignalsRecorder.this));
            noninManager.start();
            reconnectButton.setEnabled(false);
            reconnectButton.setClickable(false);
        }
    });

    // Create a folder for the recordings, and delete any extra recordings.
    File dir = new File(filesDirPath);
    if (!dir.exists()) {
        dir.mkdirs();
        File appDir = new File(appDirPath);

        // Create a list of recordings in the app directory. These
        // are named by the date on which they were formed and so can be in
        // date order (earliest first).
        String[] recordingDirs = appDir.list();
        Arrays.sort(recordingDirs);

        // How many more recordings do we have in the app directory than are
        // specified in the settings? Should account for questionnaires
        // file,
        // which must exist for the user to have gotten to this stage
        // (checklist).

        int numberRecordings = 0;
        for (String folderOrFileName : recordingDirs) {
            if (!folderOrFileName.equals(Constants.FILENAME_QUESTIONNAIRE)
                    && !folderOrFileName.equals(Constants.FILENAME_LOG_DIRECTORY)
                    && !folderOrFileName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) {
                numberRecordings++;
            }
        }

        int extraFiles = numberRecordings - Integer.parseInt(sharedPreferences
                .getString(Constants.PREF_NUMBER_RECORDINGS, Constants.DEFAULT_NUMBER_RECORDINGS));

        if (extraFiles > 0) {
            // Too many recordings. Delete the earliest n, where n is the
            // number of extra files.
            boolean success;
            int nDeleted = 0;
            for (String candidateFolderName : recordingDirs) {
                if (nDeleted >= extraFiles) {
                    // We've deleted enough already.
                    break;
                }
                if (candidateFolderName.equals(Constants.FILENAME_QUESTIONNAIRE)
                        || candidateFolderName.equals(Constants.FILENAME_LOG_DIRECTORY)
                        || candidateFolderName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) {
                    // Don't delete questionnaire file or log/feedback
                    // directory.
                    continue;
                }
                // See if the path is a directory, and skip it if it isn't.
                File candidateFolder = new File(appDir, candidateFolderName);
                if (!candidateFolder.isDirectory()) {
                    continue;
                }
                // If we've got to this stage, the file is the earliest
                // recording and should be deleted. Delete files in
                // recording first.
                success = Utils.deleteDirectory(candidateFolder);
                if (success) {
                    nDeleted++;
                }
            }
        }
    }

    // Copy latest questionnaire File
    try {
        File latestQuestionnaireFile = new File(appDirPath, Constants.FILENAME_QUESTIONNAIRE);
        InputStream in = new FileInputStream(latestQuestionnaireFile);
        OutputStream out = new FileOutputStream(new File(filesDirPath, Constants.FILENAME_QUESTIONNAIRE));
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        Log.e(Constants.CODE_APP_TAG, "FileNotFoundException copying Questionnaire file.");
    } catch (IOException e) {
        Log.e(Constants.CODE_APP_TAG, "IOException copying Questionnaire file.");
    }

    // Create txt files.
    orientationFile = new File(filesDirPath, Constants.FILENAME_ORIENTATION);
    accelerationFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_RAW);
    actigraphyFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_PROCESSED);
    audioProcessedFile = new File(filesDirPath, Constants.FILENAME_AUDIO_PROCESSED);
    bodyPositionFile = new File(filesDirPath, Constants.FILENAME_POSITION);
    ppgFile = new File(filesDirPath, Constants.FILENAME_PPG);
    spo2File = new File(filesDirPath, Constants.FILENAME_SPO2);
    audioRawFile = new File(filesDirPath, Constants.FILENAME_AUDIO_RAW);

    /** Recording starts here. */
    // Log start time so recording can begin in 30 minutes.
    startTime = Calendar.getInstance(Locale.getDefault());
    finishRecordingFlag = false;
    recordingStartDelayMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences
            .getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY));
    recordingDurationMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences
            .getString(Constants.PREF_RECORDING_DURATION, Constants.DEFAULT_RECORDING_DURATION));
    if (recordingStartDelayMs > 0) {
        startRecordingFlag = false;
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle(getString(R.string.delayAlertTitle))
                .setMessage(getString(R.string.delayAlertMessage1) + " "
                        + sharedPreferences.getString(Constants.PREF_RECORDING_START_DELAY,
                                Constants.DEFAULT_RECORDING_START_DELAY)
                        + " " + getString(R.string.delayAlertMessage2))
                .setPositiveButton(getString(R.string.ok), null);
        delayAlertDialog = dialogBuilder.create();
        delayAlertDialog.show();
    } else {
        startRecordingFlag = true;
        // Notify user
        Intent notificationIntent = new Intent(SignalsRecorder.this, SignalsRecorder.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        if (sharedPreferences.getBoolean(Constants.PREF_NOTIFICATIONS, Constants.DEFAULT_NOTIFICATIONS)) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.notification_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.deviceaccessmic))
                    .setContentTitle("SleepAp").setContentText(getString(R.string.startedRecordingNotification))
                    .setAutoCancel(false).setOngoing(true).setContentIntent(pendingIntent);
            notificationManager.notify(Constants.CODE_APP_NOTIFICATION_ID, builder.build());
            recordingSign.setVisibility(View.VISIBLE);
        }
    }

    // Start audio recording.
    if (audioEnabled) {
        extAudioRecorder = new ExtAudioRecorder(this);
        extAudioRecorder.setOutputFile(audioRawFile);
        extAudioRecorder.setShouldWrite(startRecordingFlag);
        extAudioRecorder.setAudioProcessedFile(audioProcessedFile);
        extAudioRecorder.prepare();
        extAudioRecorder.start();
    }

    // Start PPG recording.
    if (ppgEnabled && bluetoothAdapter != null) {
        String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS,
                Constants.DEFAULT_MAC_ADDRESS);
        noninManager = new NoninManager(this, bluetoothAdapter, macAddress,
                new PpgHandler(SignalsRecorder.this));
        noninManager.start();
    }

    // Start actigraphy recording.
    if (actigraphyEnabled) {
        sensorManager.registerListener(this, accelerometer, 1000000
                / (Constants.PARAM_SAMPLERATE_ACCELEROMETER * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER));
        sensorManager.registerListener(this, magnetometer, 1000000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER);
    }
    wakeLock.acquire();

    // Set up listener so that if Bluetooth connection is lost we set give
    // the user an option to reconnect.
    if (ppgEnabled) {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        registerReceiver(bluetoothDisconnectReceiver, filter);
    }

    // Start graphs update.
    graphUpdateTask = new UserInterfaceUpdater();
    graphUpdateTask.execute();
}

From source file:com.nbplus.iotapp.service.IoTService.java

@Override
public void onCreate() {
    Log.i(TAG, "debug: Creating service");
    sendBroadcast(new Intent(IoTConstants.ACTION_SERVICE_CREATE_BROADCAST));
    /**//from w  w  w.java2  s  . c  o m
     * Target we publish for clients to send messages to IncomingHandler.Note
     * that calls to its binder are sequential!
     */
    mServiceMessenger = new Messenger(mHandler);

    mUseIoTGateway = IoTServicePreference.isUseIoTGateway(this);
    if (mUseIoTGateway) {
        Log.d(TAG, ">> Use IoT Gateway....");
        // Create the Wifi lock (this does not acquire the lock, this just creates it)
        mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, IoTService.class.getSimpleName() + "_lock");

        // check network status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mBroadcastReceiver, intentFilter);

        mLastConnectionStatus = NetworkUtils.isConnected(this);

        // TODO : connect to iot gateway
        if (mThreadPooledServer != null) {
            mThreadPooledServer.stop(false);
        }
        mThreadPooledServer = new ThreadPooledServer(mServiceMessenger, IoTConstants.IOT_GATEWAY_SERVER_PORT,
                IoTConstants.IOT_GATEWAY_SERVER_THREAD_POOL_SIZE);
        new Thread(mThreadPooledServer).start();
    } else {
        Log.d(TAG, ">> Use internal blutooth....");
        // check bluetooth status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver, intentFilter);

        // bluetooth local broadcast
        intentFilter = makeGattUpdateIntentFilter();
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, intentFilter);

        // connect to ble service
        mErrorCodes = checkBluetoothEnabled();
        if (mErrorCodes.equals(IoTResultCodes.SUCCESS)) {
            try {
                if (mBluetoothServiceConnection != null) {
                    unbindService(mBluetoothServiceConnection);
                }
            } catch (Exception e) {

            }
            final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
            bindService(gattServiceIntent, mBluetoothServiceConnection, BIND_AUTO_CREATE);
        } else {
            mServiceStatus = IoTServiceStatus.STOPPED;
            Log.d(TAG, "Internal bluetooth error = " + mErrorCodes);
        }
    }
}