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:eu.liveGov.gordexola.urbanplanning.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();

    //=========== Start Camera of AR =====================
    if (_tabhost.getCurrentTab() == 2 && ARViewFragment.mFragmentIsPaused) {
        final int cameraIndex = SystemInfo.getCameraIndex(CameraInfo.CAMERA_FACING_BACK);
        ARFragment.metaioSDK.startCamera(cameraIndex, 320, 240);
        ARViewFragment.mFragmentIsPaused = false;
    }/* w  ww.j ava  2  s. c  om*/

    //------- Temperature ------------
    registerReceiver(mReceiver_Temperature, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    isReg_mReceiver_Temperature = true;

    //===========================================
    // START THE APP HERE ---------------------
    //===========================================
    if (!userinfoLoaded) {
        userinfoLoaded = true;
        UserInformationHelper uih = new UserInformationHelper();
        uih.addListener(this);
        uih.loadUserInformartion(getBaseContext(), true);
    }
}

From source file:org.protocoderrunner.apprunner.api.PDevice.java

@ProtoMethod(description = "Get the current device battery level", example = "")
@ProtoMethodParam(params = { "" })
public float battery() {
    Intent batteryIntent = getContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int 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;
    }/*from w w w .j  a v a  2s.c o  m*/

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

From source file:org.mariotaku.twidere.service.RefreshService.java

@Override
public void onCreate() {
    super.onCreate();
    GeneralComponentHelper.build(this).inject(this);
    mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    mPendingRefreshHomeTimelineIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_HOME_TIMELINE), 0);
    mPendingRefreshMentionsIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_NOTIFICATIONS), 0);
    mPendingRefreshDirectMessagesIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(BROADCAST_REFRESH_DIRECT_MESSAGES), 0);
    mPendingRefreshTrendsIntent = PendingIntent.getBroadcast(this, 0, new Intent(BROADCAST_REFRESH_TRENDS), 0);
    final IntentFilter refreshFilter = new IntentFilter(BROADCAST_NOTIFICATION_DELETED);
    refreshFilter.addAction(BROADCAST_REFRESH_HOME_TIMELINE);
    refreshFilter.addAction(BROADCAST_REFRESH_NOTIFICATIONS);
    refreshFilter.addAction(BROADCAST_REFRESH_DIRECT_MESSAGES);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_HOME_TIMELINE_REFRESHING);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_MENTIONS_REFRESHING);
    refreshFilter.addAction(BROADCAST_RESCHEDULE_DIRECT_MESSAGES_REFRESHING);
    registerReceiver(mStateReceiver, refreshFilter);
    final IntentFilter batteryFilter = new IntentFilter();
    batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    batteryFilter.addAction(Intent.ACTION_BATTERY_OKAY);
    batteryFilter.addAction(Intent.ACTION_BATTERY_LOW);
    batteryFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    batteryFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    final IntentFilter screenFilter = new IntentFilter();
    screenFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
    screenFilter.addAction(Intent.ACTION_USER_PRESENT);
    registerReceiver(mPowerStateReceiver, batteryFilter);
    registerReceiver(mScreenStateReceiver, screenFilter);
    PowerStateReceiver.setServiceReceiverStarted(true);
    if (Utils.hasAutoRefreshAccounts(this)) {
        startAutoRefresh();/*w  ww . j  a  v  a2s .c  o m*/
    } else {
        stopSelf();
    }
}

From source file:com.grarak.kerneladiutor.fragments.statistics.OverallFragment.java

@Override
public void onResume() {
    super.onResume();
    getActivity().registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

From source file:com.iss.android.wearable.datalayer.MainActivity.java

private void initializeSWBatteryChecker() {
    final TextView SWBatteryStatus = (TextView) findViewById(R.id.SWbatteryLabel);
    final Handler h = new Handler();
    final int delay = 20000; //milliseconds
    final boolean[] warned_evening = { false };

    // Timer's fine for Java, but kills android apps.

    h.postDelayed(new Runnable() {
        public void run() {
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = registerReceiver(null, ifilter);

            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

            int batteryPct = (int) (level / (float) scale * 100);
            SWBatteryStatus.setText("SW: " + batteryPct + "%");
            Calendar clnd = Calendar.getInstance();
            if (clnd.get(Calendar.HOUR_OF_DAY) >= 20) {
                if (batteryPct < 75 && !warned_evening[0]) {
                    warned_evening[0] = true;
                    displaySWBatteryWarning();
                } else if (batteryPct >= 75 && warned_evening[0]) {
                    warned_evening[0] = false;
                }//from   ww  w. ja  v a2  s  . com
            }
            h.postDelayed(this, delay);
        }
    }, 0);
}

From source file:com.thomasokken.free42.Free42Activity.java

@Override
protected void onResume() {
    super.onResume();

    // Check battery level -- this is necessary because the ACTTON_BATTERY_LOW
    // and ACTION_BATTERY_OKAY intents are not "sticky", i.e., we get those
    // notifications only when that status *changes*; we don't get any indication
    // of what that status *is* when the app is launched (or resumed?).
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if (low_battery)
        low_battery = level * 100 < scale * 20;
    else//  w ww .  j a  v a 2  s . c  om
        low_battery = level * 100 <= scale * 15;
    Rect inval = skin.update_annunciators(-1, -1, -1, -1, low_battery ? 1 : 0, -1, -1);
    if (inval != null)
        calcView.postInvalidateScaled(inval.left, inval.top, inval.right, inval.bottom);

    if (core_powercycle())
        start_core_keydown();
}

From source file:org.wso2.iot.system.service.SystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    String AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();//w w w . ja v  a2  s . com
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "IoT agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = !Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                || Preference.getBoolean(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:mx.klozz.xperience.tweaker.fragments.BatteryInfo.java

@Override
public void onResume() {
    super.onResume();
    try {/*from w w  w.j  a  v a2  s. c  o  m*/
        getActivity().registerReceiver(batteryinfoReveiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.emm.system.service.EMMSystemService.java

@Override
protected void onHandleIntent(Intent intent) {
    context = this.getApplicationContext();
    cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);
    AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME };
    if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) {
        startAdmin();//from   ww  w. j  a va  2 s .  c om
    } else {
        /*This function handles the "Execute Command on Device" Operation.
        All requests are handled on a single worker thread. They may take as long as necessary
        (and will not block the application's main thread),
        but only one request will be processed at a time.*/
        Log.d(TAG, "Entered onHandleIntent of the Command Runner Service.");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            operationCode = extras.getString("operation");

            if (extras.containsKey("command")) {
                command = extras.getString("command");
                if (command != null) {
                    restrictionCode = command.equals("true");
                }
            }

            if (extras.containsKey("appUri")) {
                appUri = extras.getString("appUri");
            }

            if (extras.containsKey("operationId")) {
                operationId = extras.getInt("operationId");
            }
        }

        if ((operationCode != null)) {
            if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) {
                Log.d(TAG, "EMM agent has sent a command with operation code: " + operationCode + " command: "
                        + command);
                doTask(operationCode);
            } else {
                Log.d(TAG, "Received command from external application. operation code: " + operationCode
                        + " command: " + command);
                boolean isAutomaticRetry;
                switch (operationCode) {
                case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY:
                    if ("false".equals(command) || "true".equals(command)) {
                        isAutomaticRetry = "true".equals(command);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isAutomaticRetry);
                        if (isAutomaticRetry) {
                            String status = Preference.getString(context,
                                    context.getResources().getString(R.string.upgrade_download_status));
                            if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_download_status),
                                        Constants.Status.FAILED);
                            } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL
                                    .equals(Preference.getString(context, context.getResources()
                                            .getString(R.string.upgrade_install_status)))) {
                                Preference.putString(context,
                                        context.getResources().getString(R.string.upgrade_install_status),
                                        Constants.Status.FAILED);
                            }
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, command); //Sending command as the message
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated");
                    } else {
                        CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST,
                                "Invalid command argument.");
                    }
                    break;
                case Constants.Operation.UPGRADE_FIRMWARE:
                    try {
                        JSONObject upgradeData = new JSONObject(command);
                        isAutomaticRetry = (Preference.hasPreferenceKey(context,
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                                && Preference.getBoolean(context,
                                        context.getResources()
                                                .getString(R.string.firmware_upgrade_automatic_retry)))
                                || !Preference.hasPreferenceKey(context, context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry));
                        if (!upgradeData.isNull(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                            isAutomaticRetry = upgradeData.getBoolean(context.getResources()
                                    .getString(R.string.firmware_upgrade_automatic_retry));
                        }
                        CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY,
                                0, (isAutomaticRetry ? "true" : "false"));
                    } catch (JSONException e) {
                        String error = "Failed to build JSON object form the request: " + command;
                        Log.e(TAG, error);
                        Preference.putString(context,
                                context.getResources().getString(R.string.upgrade_download_status),
                                Constants.Status.MALFORMED_REQUEST);
                        CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE,
                                Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error);
                        break;
                    }
                case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS:
                case Constants.Operation.GET_FIRMWARE_BUILD_DATE:
                case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS:
                    doTask(operationCode);
                    break;
                default:
                    Log.e(TAG, "Invalid operation code: " + operationCode);
                    break;
                }
            }
        }
    }
    context.registerReceiver(new BatteryChargingStateReceiver(),
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Checking is there any interrupted firmware download is there
    String status = Preference.getString(context,
            context.getResources().getString(R.string.upgrade_download_status));
    if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) {
        Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status),
                Constants.Status.REQUEST_PLACED);
        Timer timeoutTimer = new Timer();
        timeoutTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context,
                        context.getResources().getString(R.string.upgrade_download_status)))) {
                    if (Preference.getBoolean(context,
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Log.i(TAG,
                                "Found incomplete firmware download. Proceeding with last download request from the agent.");
                        OTADownload otaDownload = new OTADownload(context);
                        otaDownload.startOTA();
                    }
                }
            }
        }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT);
    }
}

From source file:com.p2p.misc.DeviceUtility.java

public float batteryLevel() {
    try {/* ww  w  .j  av a 2 s.c om*/

        BroadcastReceiver batteryReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                //  context.unregisterReceiver(this);
                Intent batteryIntent = mactivity.registerReceiver(null,
                        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                if (level == -1 || scale == -1) {
                    level = 50.0f;
                }

                if (rawlevel >= 0 && scale > 0) {
                    level = ((float) level / (float) scale) * 100.0f;
                }

                set_BatteryLevel(level);
                // Constants.BATTERY_LEVEL=level;
                System.out.println("Battery Level Remaining: " + level + "%");
            }

        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        mactivity.registerReceiver(batteryReceiver, filter);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return level;
}