/ * This method checks forpower by comparing the current battery state against all possible * plugged in states. In thiscase, a device may be considered plugged in either by USB, AC, or * wireless charge. (Wireless charge was introduced in API Level 17.) */ privateboolean checkForPower() { // It is very easy to subscribe to changes to the battery state, but you can get the current // state by simply passing null in as your receiver. Nifty, isn't that? IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.registerReceiver(null, filter);
// There are currently three ways a device can be plugged in. We should check them all. int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean usbCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_USB); boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC); boolean wirelessCharge = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { wirelessCharge = (chargePlug ==BatteryManager.BATTERY_PLUGGED_WIRELESS); } return (usbCharge || acCharge || wirelessCharge); }
public classWakefulReceiverextendsWakefulBroadcastReceiver{
@Override public void onReceive(Context context, Intent intent) {
// Start the service, keeping the device awake while the service is // launching. This is the Intent to deliver to the service. Intent service = newIntent(context, WakefulService.class); startWakefulService(context, service); } } public classWakefulServiceextendsIntentService{ public WakefulService() { super("WakefulService"); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); // Do the work that requires your app to keep the CPU running. // ... // Release the wake lock provided by the WakefulBroadcastReceiver. MyWakefulReceiver.completeWakefulIntent(intent); } }