Example usage for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED

List of usage examples for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED

Introduction

In this page you can find the example usage for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED.

Prototype

String ACTION_ACL_CONNECTED

To view the source code for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED.

Click Source Link

Document

Broadcast Action: Indicates a low level (ACL) connection has been established with a remote device.

Usage

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

/**
 * Called when the activity is first created. onStart() is called
 * immediately afterwards./* www .  ja  va 2s.co 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:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

public IntentFilter declareIntentFilters() {
    IntentFilter intentFilter = new IntentFilter(IntentHandler.UPDATE_ACTION);
    intentFilter.addAction(IntentHandler.START_TRACKING_ACTION);
    intentFilter.addAction(IntentHandler.TRACK_REMOTE);
    intentFilter.addAction(IntentHandler.STOP_TRACKING_ACTION);
    intentFilter.addAction(IntentHandler.SPEED_TEST);
    intentFilter.addAction(IntentHandler.RUN_WEBSOCKET);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_START_UI);

    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_LOCATION_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_CELL_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_GPS_STATUS_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_SIGNAL_STRENGTH_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_EVENT_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_NEIGHBOR_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_NETWORK_UPDATE);
    //intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_RX_TX);

    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_RESULT);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_ERROR);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_COMPLETE);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_CANCELLED);

    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_RESULT);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_ERROR);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_COMPLETE);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_CANCELLED);

    //do not add filter if sms test permissions aren't all allowed
    if (PreferenceKeys.getSMSPermissionsAllowed(owner, true))
        intentFilter.addAction(IntentHandler.SMS_TEST);

    intentFilter.addAction(IntentHandler.SMS_DELIVERED);
    intentFilter.addAction(IntentHandler.LATENCY_TEST);
    intentFilter.addAction(IntentHandler.ACTION_STOP_SPEEDTEST);
    intentFilter.addAction(IntentHandler.RESTART_MMC_SERVICE);
    intentFilter.addAction(IntentHandler.COLDRESET_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(IntentHandler.COMMAND);
    intentFilter.addAction(IntentHandler.SURVEY);
    //intentFilter.addAction(Intent.ACTION_VIEW);
    //intentFilter.addAction("android.intent.PHONE_STATE");
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_TRACKING_5MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_TRACKING_1MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_3HOUR);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_15MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_SCANAPPS);
    intentFilter.addAction(IntentHandler.EMAIL_CSV);
    intentFilter.addAction(IntentHandler.GPS_STATE_OFF);
    intentFilter.addAction(IntentHandler.GPS_STATE_ON);
    intentFilter.addAction(IntentHandler.PHONE_CALL_CONNECT);
    intentFilter.addAction(IntentHandler.PHONE_CALL_DISCONNECT);
    intentFilter.addAction(IntentHandler.HANDOFF);
    //intentFilter.addAction(IntentHandler.SMS_SENT);
    intentFilter.addAction(IntentHandler.SMS_RECEIVED);
    intentFilter.addAction(Intent.ACTION_SEND);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_START);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_END);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_CANCEL);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_START);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_END);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_CANCEL);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

    intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
    intentFilter.addAction(IntentHandler.ROAMING_ON);
    intentFilter.addAction(IntentHandler.ROAMING_OFF);

    intentFilter.addAction(IntentHandler.VIEWING_SIGNAL);
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    intentFilter.addAction("android.intent.action.PRECISE_CALL_STATE");
    intentFilter.addAction("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED");
    intentFilter.addAction("android.intent.action.PHONE_STATE");
    intentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");

    intentFilter.addAction("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN");
    intentFilter.addAction("android.intent.action.ANY_DATA_STATE");
    intentFilter.addAction("android.intent.action.ACTION_DATA_CONNECTION_FAILED");

    intentFilter.addAction(CommonIntentActionsOld.ACTION_BLUETOOTH_ENDDOWNLOAD);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_START_VOICETEST);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_STOP_VOICETEST);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE);

    intentFilter.addAction(IntentHandler.ACTIVE_TEST);
    intentFilter.addAction(IntentHandler.ACTION_STOP_VIDEOTEST);
    intentFilter.addAction(IntentHandler.GCM_MESSAGE);

    intentFilter.addAction("org.restcomm.android.CONNECT_FAILED");
    intentFilter.addAction("org.restcomm.android.CALL_STATE");
    intentFilter.addAction("org.restcomm.android.DISCONNECT_ERROR");

    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_DISCONNECT);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_CONNECT);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_NEIGHBORS);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_SERVICEMODE);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_SERVICEMENU);
    intentFilter.addAction(IntentHandler.ACTION_MMCSYS_VERSION);

    //intentFilter.addAction(Intent.ACTION_APP_ERROR);
    int raisePriority = owner.getPackageManager().checkPermission("android.permission.RAISED_THREAD_PRIORITY",
            owner.getPackageName());//  www .j  ava  2s .co m
    // With permission to raise priority for SMS messages
    if (raisePriority == 0)
        intentFilter.setPriority(9999999);

    return intentFilter;
}