Example usage for android.content Intent ACTION_BATTERY_CHANGED

List of usage examples for android.content Intent ACTION_BATTERY_CHANGED

Introduction

In this page you can find the example usage for android.content Intent ACTION_BATTERY_CHANGED.

Prototype

String ACTION_BATTERY_CHANGED

To view the source code for android.content Intent ACTION_BATTERY_CHANGED.

Click Source Link

Document

Broadcast Action: This is a sticky broadcast containing the charging state, level, and other information about the battery.

Usage

From source file:de.schildbach.wallet.marscoin.service.BlockchainServiceImpl.java

@Override
public void onCreate() {
    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//from  ww  w  . j av a  2  s. c o m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("marscoin", "Couldn't find checkpoints file; starting from genesis");
            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

From source file:de.schildbach.wallet.elysium.service.BlockchainServiceImpl.java

@Override
public void onCreate() {

    Log.d(TAG, ".onCreate()");

    super.onCreate();

    nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
    wifiLock.setReferenceCounted(false);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    final int versionCode = application.applicationVersionCode();
    prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);/*from www  .  ja v  a 2  s.  c o  m*/

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE),
            Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        Log.d(TAG, "blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        copyBlockchainSnapshot(blockChainFile);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);

        if (!blockChainFileExists) { // Starting from scratch
            try {
                final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();
                final InputStream checkpointsFileIn = getAssets().open("checkpoints");
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsFileIn, blockStore,
                        earliestKeyCreationTime);
            } catch (IOException e) {
                Log.d("Elysium", "Couldn't find checkpoints file; starting from genesis");

            }
        }
        blockStore.getChainHead(); // detect corruptions as early as possible

    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        x.printStackTrace();

        throw new Error("blockstore cannot be created", x);
    } catch (final NullPointerException x) {
        blockChainFile.delete();

        x.printStackTrace();
        throw new Error("blockstore cannot be created", x);
    }

    try {

        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);

    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

private int calculateBatteryLevel(Context context) {
    Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
    return level * 100 / scale;
}

From source file:com.lemon.lime.MainActivity.java

private void getBatteryPercentage() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

            if (currentLevel >= 0 && scale > 0) {
                level = (currentLevel * 100) / scale;
            }//from w  w  w  . j a  v a 2  s . c om
        }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}

From source file:it.unipr.ce.dsg.gamidroid.activities.NAM4JAndroidActivity.java

@Override
public void onStart() {

    super.onStart();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();/*from  www.j  av a  2 s . com*/

    // Registering the broadcast receivers
    //registerReceiver(bReceiver, new IntentFilter(Constants.RECEIVED_RESOURCES_UPDATE));

    registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

}

From source file:csic.ceab.movelab.beepath.Util.java

public static int getBatteryLevel(Context context) {
    Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra("level", -1);
    int scale = batteryIntent.getIntExtra("scale", -1);

    // Error checking that probably isn't needed but I added just in case.
    if (level == -1 || scale == -1) {
        return -1;
    }//from  w w  w . ja  v a  2  s .c  o m

    int powerLevel = (int) Math.round(level * 100.0 / scale);

    return powerLevel;
}

From source file:saphion.services.ForegroundService.java

@SuppressWarnings("deprecation")
@Override/* w ww . j a v  a 2 s .  c  om*/
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:in.codehex.arrow.MainActivity.java

/**
 * Get the battery status of the device/*from www  . j a  v a2 s  .  co m*/
 *
 * @return the battery level of the device
 */
private float getBatteryLevel() {
    Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = -1, scale = -1;
    if (batteryIntent != null) {
        level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    }

    // Error checking that probably isn't needed but I added just in case.
    if (level == -1 || scale == -1) {
        return 50.0f;
    }

    return ((float) level / (float) scale) * 100.0f;
}

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

/**
 * Called when the activity is first created. onStart() is called
 * immediately afterwards./*from w  w  w .java  2s  . c  om*/
 */
@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:og.android.tether.MainActivity.java

public MainActivity() {

    intentReceiver = new BroadcastReceiver() {
        @Override//from  w w  w  .  j  ava  2  s .  c o m
        public void onReceive(Context context, Intent intent) {
            Log.d(MSG_TAG, "onReceive() " + intent);
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
                int temp = (intent.getIntExtra("temperature", 0));
                MainActivity.this.application.lastTemperature = temp;
                int celsius = (int) ((temp + 5) / 10);
                int fahrenheit = (int) (((temp / 10) / 0.555) + 32 + 0.5);
                Log.d(MSG_TAG,
                        "Temp ==> " + temp + " -- Celsius ==> " + celsius + " -- Fahrenheit ==> " + fahrenheit);
                if (MainActivity.this.application.settings.getString("batterytemppref", "celsius")
                        .equals("celsius")) {
                    batteryTemperature
                            .setText("" + celsius + getString(R.string.main_activity_temperatureunit_celsius));
                } else {
                    batteryTemperature.setText(
                            "" + fahrenheit + getString(R.string.main_activity_temperatureunit_fahrenheit));
                }
            } else {
                //Log.d(MSG_TAG, "INTENT RECEIVED: "+intent.getAction());
                if (action.equals(TetherService.INTENT_TRAFFIC))
                    updateTrafficDisplay(intent.getLongArrayExtra("traffic_count"));
                if (action.equals(TetherService.INTENT_STATE)) {
                    Log.d(MSG_TAG, "STATE RECEIVED: " + intent.getIntExtra("state", 999));
                    try {
                        switch (intent.getIntExtra("state", TetherService.STATE_IDLE)) {
                        case TetherService.STATE_RESTARTING:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STOPPING);
                            } catch (Exception e) {
                            }
                            break;
                        case TetherService.STATE_STARTING:
                            MainActivity.this.showDialog(MainActivity.ID_DIALOG_STARTING);
                            break;
                        case TetherService.STATE_RUNNING:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STARTING);
                            } catch (Exception e) {
                            }
                            MainActivity.this.toggleStartStop();
                            break;
                        case TetherService.STATE_STOPPING:
                            MainActivity.this.showDialog(MainActivity.ID_DIALOG_STOPPING);
                            break;
                        case TetherService.STATE_IDLE:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STOPPING);
                            } catch (Exception e) {
                            }
                            MainActivity.this.toggleStartStop();
                            break;
                        case TetherService.STATE_FAIL_LOG:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STARTING);
                            } catch (Exception e) {
                            }
                            MainActivity.this.application
                                    .displayToastMessage(getString(R.string.main_activity_start_errors));
                            MainActivity.this.toggleStartStop();
                            break;
                        case TetherService.STATE_FAIL_EXEC_START:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STARTING);
                            } catch (Exception e) {
                            }
                            MainActivity.this.application
                                    .displayToastMessage(getString(R.string.main_activity_start_unable));
                            MainActivity.this.toggleStartStop();
                            break;
                        case TetherService.STATE_FAIL_EXEC_STOP:
                            try {
                                MainActivity.this.dismissDialog(MainActivity.ID_DIALOG_STOPPING);
                            } catch (Exception e) {
                            }
                            MainActivity.this.toggleStartStop();
                            break;
                        }

                    } catch (Exception e) {
                    } finally {
                        // MainActivity.this.toggleStartStop();
                    }

                } else if (action.equals(RSSReader.MESSAGE_JSON_RSS)) {
                    updateRSSView(intent.getStringExtra(RSSReader.EXTRA_JSON_RSS));
                }
            }

        }
    };

    // ??? deprecated?
    viewUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d(MSG_TAG, "MESSAGE: " + msg);
            switch (msg.what) {
            case MESSAGE_CHECK_LOG:
                Log.d(MSG_TAG, "Error detected. Check log.");
                MainActivity.this.application
                        .displayToastMessage(getString(R.string.main_activity_start_errors));
                MainActivity.this.toggleStartStop();
                break;
            case MESSAGE_CANT_START_TETHER:
                Log.d(MSG_TAG, "Unable to start tethering!");
                MainActivity.this.application
                        .displayToastMessage(getString(R.string.main_activity_start_unable));
                MainActivity.this.toggleStartStop();
                break;
            case MESSAGE_TRAFFIC_START:
                MainActivity.this.trafficRow.setVisibility(View.VISIBLE);
                break;
            case MESSAGE_TRAFFIC_COUNT:
                MainActivity.this.trafficRow.setVisibility(View.VISIBLE);
                //???
                long uploadTraffic = ((TetherService.DataCount) msg.obj).totalUpload;
                long downloadTraffic = ((TetherService.DataCount) msg.obj).totalDownload;
                long uploadRate = ((TetherService.DataCount) msg.obj).uploadRate;
                long downloadRate = ((TetherService.DataCount) msg.obj).downloadRate;

                // Set rates to 0 if values are negative
                if (uploadRate < 0)
                    uploadRate = 0;
                if (downloadRate < 0)
                    downloadRate = 0;

                MainActivity.this.uploadText.setText(MainActivity.this.formatCount(uploadTraffic, false));
                MainActivity.this.downloadText.setText(MainActivity.this.formatCount(downloadTraffic, false));
                MainActivity.this.downloadText.invalidate();
                MainActivity.this.uploadText.invalidate();

                MainActivity.this.uploadRateText.setText(MainActivity.this.formatCount(uploadRate, true));
                MainActivity.this.downloadRateText.setText(MainActivity.this.formatCount(downloadRate, true));
                MainActivity.this.downloadRateText.invalidate();
                MainActivity.this.uploadRateText.invalidate();
                break;
            case MESSAGE_TRAFFIC_END:
                MainActivity.this.trafficRow.setVisibility(View.INVISIBLE);
                break;
            case MESSAGE_DOWNLOAD_STARTING:
                Log.d(MSG_TAG, "Start progress bar");
                MainActivity.this.progressBar.setIndeterminate(true);
                MainActivity.this.progressTitle.setText((String) msg.obj);
                MainActivity.this.progressText.setText("Starting...");
                MainActivity.this.downloadUpdateLayout.setVisibility(View.VISIBLE);
                break;
            case MESSAGE_DOWNLOAD_PROGRESS:
                MainActivity.this.progressBar.setIndeterminate(false);
                MainActivity.this.progressText.setText(msg.arg1 + "k /" + msg.arg2 + "k");
                MainActivity.this.progressBar.setProgress(msg.arg1 * 100 / msg.arg2);
                break;
            case MESSAGE_DOWNLOAD_COMPLETE:
                Log.d(MSG_TAG, "Finished download.");
                MainActivity.this.progressText.setText("");
                MainActivity.this.progressTitle.setText("");
                MainActivity.this.downloadUpdateLayout.setVisibility(View.GONE);
                break;
            case MESSAGE_DOWNLOAD_BLUETOOTH_COMPLETE:
                Log.d(MSG_TAG, "Finished bluetooth download.");
                MainActivity.this.startBtn.setClickable(true);
                MainActivity.this.radioModeLabel.setText("Bluetooth");
                break;
            case MESSAGE_DOWNLOAD_BLUETOOTH_FAILED:
                Log.d(MSG_TAG, "FAILED bluetooth download.");
                MainActivity.this.startBtn.setClickable(true);
                MainActivity.this.application.preferenceEditor.putBoolean("bluetoothon", false);
                MainActivity.this.application.preferenceEditor.commit();
                // TODO: More detailed popup info.
                MainActivity.this.application.displayToastMessage(
                        "No bluetooth module for your kernel! Please report your kernel version.");
            default:
                MainActivity.this.toggleStartStop();
            }
            super.handleMessage(msg);
        }
    };

}