Java Code Examples for android.content.Intent.ACTION_BATTERY_CHANGED

The following are Jave code examples for showing how to use ACTION_BATTERY_CHANGED of the android.content.Intent class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Xndroid   File: XndroidReceiver.java   View Source Code Vote up 9 votes
@Override
public void onReceive(Context context, Intent intent) {
    try {
        String action = intent.getAction();
        if(action == Intent.ACTION_BATTERY_CHANGED){
            handleBattery(intent);
        }else if(action == ConnectivityManager.CONNECTIVITY_ACTION){
            AppModel.getNetworkState();
        }else if(action == Intent.ACTION_SCREEN_ON){
            AppModel.sDevScreenOff = false;
            LogUtils.i("screen on");
        }else if(action == Intent.ACTION_SCREEN_OFF){
            AppModel.sDevScreenOff = true;
            LogUtils.i("screen off");
        }
    }catch (Exception e){
        LogUtils.e("onReceive error ", e);
    }

}
 
Example 2
Project: JobSchedulerCompat   File: DeviceTestUtils.java   View Source Code Vote up 7 votes
@SuppressWarnings("deprecation")
public static void setCharging(Context context, boolean charging) {
    Intent chargingIntent = new Intent(Intent.ACTION_BATTERY_CHANGED);
    if (charging) {
        chargingIntent.putExtra(BatteryManager.EXTRA_PLUGGED, BatteryManager.BATTERY_PLUGGED_AC);
    }
    context.sendStickyBroadcast(chargingIntent);
}
 
Example 3
Project: chromium-net-for-android   File: PowerMonitor.java   View Source Code Vote up 7 votes
/**
 * Create a PowerMonitor instance if none exists.
 * @param context The context to register broadcast receivers for.  The application context
 *                will be used from this parameter.
 */
public static void create(Context context) {
    context = context.getApplicationContext();
    if (sInstance == null) {
        sInstance = LazyHolder.INSTANCE;
        ApplicationStatus.registerApplicationStateListener(sInstance);
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
        if (batteryStatusIntent != null) onBatteryChargingChanged(batteryStatusIntent);
    }
}
 
Example 4
Project: buildAPKsApps   File: MainSettingsActivity.java   View Source Code Vote up 7 votes
protected void onResume() {
	super.onResume();

	updateMemoryStatus();

	// register common receiver
	IntentFilter filter = mCommonIntentFilter;
	if (filter == null) {
		filter = mCommonIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		filter.addAction(LedFlashlightReceiver.ACTION_FLASHLIGHT);
		mCommonIntentReceiver = new CommonIntentReceiver();
	}
	registerReceiver(mCommonIntentReceiver, filter);

	// create/initialize/activate handlers
	createInitializeActivateHandlers();
	mLayout.updateLayout(this);
	updateFlashlightView();

	if (mRestartRequired) {
		finish();
		Intent intent = new Intent(Constants.ACTION_START_QS);
		sendBroadcast(intent);
	}
}
 
Example 5
Project: buildAPKsApps   File: Main.java   View Source Code Vote up 7 votes
private void batteryLevelUpdater()
{
    batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            //context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int level = -1;
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale;
            }
            mBatteryLevelView.setLevel(level);
        }
    };
    batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
 
Example 6
Project: decoy   File: CrashSnapshot.java   View Source Code Vote up 7 votes
/**
 * 获取手机剩余电量
 * 
 * @return
 */
private static String battery() {
	IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	Intent intent = NimUIKit.getContext().registerReceiver(null, filter);
	int level = intent.getIntExtra("level", -1);
	int scale = intent.getIntExtra("scale", -1);
	if(scale == -1) {
		return "--";
	} else {
		return String.format(Locale.US, "%d %%", (level*100) / scale);
	}
}
 
Example 7
Project: thingplug-sdk-android   File: SensorListener.java   View Source Code Vote up 7 votes
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction() == Intent.ACTION_BATTERY_CHANGED) {
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        float temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;
        float chargeLevel = ((float) (level * 100)) / scale;

        for (SensorInfo sensorInfo : sensorInfos) {
            if (sensorInfo.getType() == SensorType.BATTERY) {
                sensorInfo.setValues(new float[]{temperature, chargeLevel});
                break;
            }
        }
    }
}
 
Example 8
Project: gpstracker-android   File: BatteryRecorder.java   View Source Code Vote up 6 votes
private void recordBatteryLevel() {
    Log.i(TAG, "Record battery level");

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = mContext.registerReceiver(null, ifilter);

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

    float batteryPct = (level / (float) scale) * 100;
    mTelemetry.write(Telemetry.BATTERY_TAG, String.valueOf(batteryPct));
}
 
Example 9
Project: 2017.2-codigo   File: BateriaActivity.java   View Source Code Vote up 6 votes
@Override
protected void onStart() {
    super.onStart();
    IntentFilter f=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(onBattery, f);

}
 
Example 10
Project: Lantern-sdk   File: RylaInstrumentation.java   View Source Code Vote up 6 votes
private float getBatteryPercent() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = RYLA.getInstance().getContext().registerReceiver(null, ifilter);

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

    return level / (float)scale * 100;
}
 
Example 11
Project: mapbox-events-android   File: MapEventFactory.java   View Source Code Vote up 6 votes
private Intent registerBatteryUpdates(Context context) {
  IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  return context.registerReceiver(null, filter);
}
 
Example 12
Project: chromium-for-android-56-debug-video   File: OfflinePageUtils.java   View Source Code Vote up 6 votes
/** Returns the current device conditions. May be overridden for testing. */
protected DeviceConditions getDeviceConditionsImpl(Context context) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    // Note this is a sticky intent, so we aren't really registering a receiver, just getting
    // the sticky intent.  That means that we don't need to unregister the filter later.
    Intent batteryStatus = context.registerReceiver(null, filter);
    if (batteryStatus == null) return null;

    // Get the connection type from chromium's internal object.
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();

    // Sometimes the NetworkConnectionNotifier lags the actual connection type, especially when
    // the GCM NM wakes us from doze state.  If we are really connected, report the connection
    // type from android.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        // Get the connection type from android in case chromium's type is not yet set.
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if (isConnected) {
            connectionType = convertAndroidNetworkTypeToConnectionType(activeNetwork.getType());
        }
    }

    return new DeviceConditions(
            isPowerConnected(batteryStatus), batteryPercentage(batteryStatus), connectionType);
}
 
Example 13
Project: microbit   File: BatteryPresenter.java   View Source Code Vote up 6 votes
@Override
public void start() {
    if(!isRegistered) {
        isRegistered = true;
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        application.registerReceiver(batteryReceiver, filter);

        if(informationPlugin != null) {
            CmdArg cmd = new CmdArg(0, "Registered Battery.");
            informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
        }
    }
}
 
Example 14
Project: Telephoto   File: BatteryReceiver.java   View Source Code Vote up 6 votes
@Override
public void onReceive(Context context, Intent intent) {
    String message = null;
    switch (intent.getAction()) {
        case Intent.ACTION_BATTERY_LOW:
            if (!isSentBatteryLow) {
                message = botService.getString(R.string.battery_low);
                isSentBatteryLow = true;
            }
            break;
        case Intent.ACTION_BATTERY_OKAY:
            isSentBatteryLow = false;
            break;
        case Intent.ACTION_POWER_DISCONNECTED:
            message = botService.getString(R.string.power_disconnected) + getStatus();
            break;
        case Intent.ACTION_POWER_CONNECTED:
            message = botService.getString(R.string.power_connected);
            break;
        case Intent.ACTION_BATTERY_CHANGED:
            mBatteryLevel = getBatteryLevel(intent);
            mPowerStatus = getBatteryStatus(intent);
            ReceiverStorage.getInstance().setBatteryLevel(mBatteryLevel);
            int segment = getSegment(mBatteryLevel);
            if (segment < lastSegmentNotify) {
                String attention = mIsCharging ? botService.getString(R.string.battery_discharging) : "";
                message = attention + getStatus();
            }
            lastSegmentNotify = segment;
            break;
    }
    if (message != null) {
        botService.getTelegramService().sendMessageToAll(message);
    }
}
 
Example 15
Project: PlayerBase   File: DefaultPlayerControllerCover.java   View Source Code Vote up 6 votes
private void initBatteryReceiver(Context context) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    batteryReceiver = new BatteryReceiver();
    if(context!=null){
        context.registerReceiver(batteryReceiver,filter);
    }
}
 
Example 16
Project: DeviceInfo   File: BatteryFragment.java   View Source Code Vote up 6 votes
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_battery, container, false);
    unbinder = ButterKnife.bind(this, view);

    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    mActivity.registerReceiver(mBatInfoReceiver, filter);
    IntentFilter filter2 = new IntentFilter(Intent.ACTION_BATTERY_LOW);
    mActivity.registerReceiver(mBatLow, filter2);
    return view;
}
 
Example 17
Project: homeDash   File: SensorReader.java   View Source Code Vote up 6 votes
public  void getBatteryReading(SensorDataListener listener){

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, intentFilter);

        int batteryStatusIntExtra = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = batteryStatusIntExtra == BatteryManager.BATTERY_STATUS_CHARGING ||
                batteryStatusIntExtra == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

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

        float batteryPct = level / (float)scale;

        Log.i(TAG, "AC connected: "+acCharge);
        Log.i(TAG, "USB connected: "+usbCharge);
        Log.i(TAG, "Battery charging: "+ isCharging);
        Log.i(TAG, "Battery Level: "+ batteryPct);

        ArrayMap<String, String> map = new ArrayMap<>(3);
        map.put(SENSOR, "Battery");
        map.put(VALUE, Integer.toString(level));
        map.put(UNIT, BATTERYSENSOR_UNIT);
        map.put("charging", Boolean.toString(isCharging));
        map.put("acPlugged", Boolean.toString(acCharge));
        map.put("usbPlugged", Boolean.toString(usbCharge));
        listener.sensorData(map);
    }
 
Example 18
Project: network-kit-android   File: NetworkAwareVideoPreloader.java   View Source Code Vote up 5 votes
public boolean doScheduleImmediateNetworkCheck(final Context ctx,
                                               Listener userHandler,
                                               final Constraint constraint1,
                                               final Constraint constraint2) {

    if (userHandler == null) {
        Log.w(TAG, "Invalid argument: Listener object should NOT be null");
        return false;
    }

    MeasureManager.MeasurementCompletedListener internalHandler = null;
    boolean isUserHandlerAlreadyRegistered = false;

    for (MeasureManager.MeasurementCompletedListener mcl : mListenersImmediate.keySet()) {
        if (mListenersImmediate.get(mcl) == userHandler) {
            internalHandler = mcl;
            isUserHandlerAlreadyRegistered = true;
        }
    }

    if (!isUserHandlerAlreadyRegistered) {

        // Create a new internal measurement handler
         internalHandler = new MeasureManager.MeasurementCompletedListener() {
            @Override
            public void onMeasurementComplete(MeasureSample measureSample) {
                boolean isItGoodForVideo = false;
                Log.d(TAG, "Network sampling OK : " + measureSample.testOk
                                        + ", type = " + measureSample.networkType
                                        + ", name = " + measureSample.networkName
                                        + ", quality = " + measureSample.networkState);
                // Rule 1
                if (constraint1 == Constraint.NETWORK_FAST_FOR_MEDIA_DOWNLOAD) {
                    if (measureSample.testOk &&
                            (measureSample.networkState == ConnectionQuality.EXCELLENT || measureSample.networkState == ConnectionQuality.GOOD)) {
                        isItGoodForVideo = true;
                        Log.d(TAG, "Criteria1: Network conditions are good");
                    }
                }
                // Rule 2
                if (constraint2 == Constraint.NETWORK_DEVICE_CHARGING) {
                    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                    Intent batteryStatus = ctx.registerReceiver(null, ifilter);
                    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;
                    isItGoodForVideo = isItGoodForVideo && isCharging;
                }

                Log.d(TAG, "Final determination: All criteria met? : " + isItGoodForVideo);

                Listener userHandler = mListenersImmediate.get(this);
                if (userHandler != null) {
                    try {
                        // Invoke the user's installed handler with the YES or NO answer
                        // WARN: This method may be slow/time-consuming.
                        userHandler.OnNetworkSuitableForCriteria(isItGoodForVideo);
                    } catch (Exception e) {
                        Log.w(TAG, e.getMessage());
                    }
                }
            }
        };

        // Add it to the map
        mListenersImmediate.put(internalHandler, userHandler);
    }


    MeasureManager manager = MeasureManager.getInstance();
    manager.init(ctx);
    manager.register(internalHandler);
    Log.d(TAG, "Triggering network measurement");
    manager.measureOnce(ctx, "_VID");
    return true;
}
 
Example 19
Project: LockScreen-Oreo   File: LockedScreen.java   View Source Code Vote up 5 votes
public void run()

        {
            SimpleDateFormat sdf = new SimpleDateFormat("EEEE, dd MMMM");
            Date d = new Date();
            String dayOfTheWeek = sdf.format(d);
            txtDate.setText(dayOfTheWeek);

            SimpleDateFormat ap = new SimpleDateFormat("HH");
            Date t = new Date();
            String dayTime = ap.format(t);
            st = (ImageView) findViewById(R.id.ampm);
            if (Integer.parseInt(dayTime) > Integer.parseInt("06") && Integer.parseInt(dayTime) < Integer.parseInt("18")) {
                st.setImageResource(R.drawable.sun);
            } else {
                st.setImageResource(R.drawable.moon);
            }


            BroadcastReceiver batteryLevel = 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);
                    int level = -1;
                    if (currentLevel >= 0 && scale > 0) {
                        level = (currentLevel * 100) / scale;
                    }
                    batteryStatus.setText(level + "%");
                }
            };

            IntentFilter batteryLevelFilter = new IntentFilter(
                    Intent.ACTION_BATTERY_CHANGED);
            registerReceiver(batteryLevel, batteryLevelFilter);


            mHandler.postDelayed(m_Runnable, 500);

        }
 
Example 20
Project: phonk   File: PDevice.java   View Source Code Vote up 5 votes
/**
 * Gets a callback each time there is a change in the battery status
 * @param callback
 *
 * @status TODO_EXAMPLE
 */
@ProtoMethod
public void battery(final ReturnInterface callback) {
    batteryReceiver = new BroadcastReceiver() {
        int scale = -1;
        int level = -1;
        int voltage = -1;
        int temp = -1;
        boolean isConnected = false;
        private int status;
        private final boolean alreadyKilled = false;

        @Override
        public void onReceive(Context context, Intent intent) {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
            // isCharging =
            // intent.getBooleanExtra(BatteryManager.EXTRA_PLUGGED, false);
            // status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            status = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

            if (status == BatteryManager.BATTERY_PLUGGED_AC) {
                isConnected = true;
            } else if (status == BatteryManager.BATTERY_PLUGGED_USB) {
                isConnected = true;
            } else {
                isConnected = false;
            }

            ReturnObject o = new ReturnObject();

            o.put("level", level);
            o.put("temperature", temp);
            o.put("connected", isConnected);
            o.put("scale", scale);
            o.put("temperature", temp);
            o.put("voltage", voltage);

            callback.event(o);
        }
    };

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