Java Code Examples for android.os.PowerManager#WakeLock

The following examples show how to use android.os.PowerManager#WakeLock . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {

    final PowerManager.WakeLock wakeLock1 = JoH.getWakeLock("DexCollectionService", 60000);
    try {
        final byte[] data = characteristic.getValue();

        if (data != null && data.length > 0) {
            setSerialDataToTransmitterRawData(data, data.length);

            final String hexdump = HexDump.dumpHexString(data);
            //if (!hexdump.contains("0x00000000 00      ")) {
            if (data.length > 1 || data[0] != 0x00) {
                static_last_hexdump = hexdump;
            }
            if (d) Log.i(TAG, "onCharacteristicChanged entered " + hexdump);

        }
        lastdata = data;

        Inevitable.task("dex-set-failover", 1000, () -> {
            setFailoverTimer(); // restart the countdown
            // intentionally left hanging wakelock for 5 seconds after we receive something
            final PowerManager.WakeLock wakeLock2 = JoH.getWakeLock("DexCollectionLinger", 5000);
        });

    } finally {
       /* if (Pref.getBoolean("bluetooth_frequent_reset", false)) {
            Log.e(TAG, "Resetting bluetooth due to constant reset option being set!");
            JoH.restartBluetooth(getApplicationContext(), 5000);
        }*/
        JoH.releaseWakeLock(wakeLock1);
    }
}
 
Example 2
Source File: CbAlarm.java    From PressureNet-SDK with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	PowerManager pm = (PowerManager) context
			.getSystemService(Context.POWER_SERVICE);
	PowerManager.WakeLock wl = pm.newWakeLock(
			PowerManager.PARTIAL_WAKE_LOCK, "");
	wl.acquire();

	Intent serviceIntent = new Intent(context, CbService.class);
	serviceIntent.putExtra("alarm", true);
	context.startService(serviceIntent);
	
	wl.release();
}
 
Example 3
Source File: WidgetUpdateService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context ctx, Intent intent) {
    final PowerManager.WakeLock wl = JoH.getWakeLock("xdrip-widget-bcast", 20000);
    //Log.d(TAG, "onReceive("+intent.getAction()+")");
    if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) {
        updateCurrentBgInfo();
    } else if (intent.getAction().compareTo(Intent.ACTION_SCREEN_ON) == 0) {
        enableClockTicks();
        updateCurrentBgInfo();
    } else if (intent.getAction().compareTo(Intent.ACTION_SCREEN_OFF) == 0) {
        disableClockTicks();
    }
    JoH.releaseWakeLock(wl);
}
 
Example 4
Source File: Helper.java    From Learning-Resources with MIT License 5 votes vote down vote up
/**
 * Show the activity over the lockscreen and wake up the device. If you launched the app
 * manually both of these conditions are already true. If you deployed from the IDE, however,
 * this will save you from hundreds of power button presses and pattern swiping per day!
 */
public static void riseAndShine(Activity activity) {
    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    PowerManager power = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock lock = power.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "wakeup!");

    lock.acquire(100000);
    lock.release();
}
 
Example 5
Source File: MD5_jni.java    From stynico with MIT License 5 votes vote down vote up
private void wakeUpAndUnlock(Context context)
{
	KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
	KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
	// 解锁
	kl.disableKeyguard();
	// 获取电源管理器对象
	PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
	// 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
	PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
	// 点亮屏幕
	wl.acquire();
	// 释放
	wl.release();
}
 
Example 6
Source File: LogToFile.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static void appendLog(Context context, String tag, String text1, PowerManager.WakeLock value1, String text2, boolean value2) {
    checkPreferences(context);
    if (!logToFileEnabled || (logFilePathname == null)) {
        return;
    }
    appendLog(context, tag, text1, (value1 != null)? value1.toString() : "null", text2, String.valueOf(value2));
}
 
Example 7
Source File: WakeLockManager.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Releases the wake lock identified by the {@code key} if it is currently held.
 */
public void release(Object key) {
  synchronized (LOCK) {
    cleanup();
    Preconditions.checkNotNull(key, "Key can not be null");
    PowerManager.WakeLock wakelock = getWakeLock(key);

    // If the lock is not held (if for instance there is a wake lock timeout), we cannot release
    // again without triggering a RuntimeException.
    if (!wakelock.isHeld()) {
      logger.warning("Over-release of wakelock: %s", key);
      return;
    }

    // We held the wake lock recently, so it's likely safe to release it. Between the isHeld()
    // check and the release() call, the wake lock may time out however and we catch the resulting
    // RuntimeException.
    try {
      wakelock.release();
    } catch (RuntimeException exception) {
      logger.warning("Over-release of wakelock: %s, %s", key, exception);
    }
    log(key, "released");

    // Now if the lock is not held, that means we were the last holder, so we should remove it
    // from the map.
    if (!wakelock.isHeld()) {
      wakeLocks.remove(key);
      log(key, "freed");
    }
  }
}
 
Example 8
Source File: WakeLockMetricsCollectorTest.java    From Battery-Metrics with MIT License 5 votes vote down vote up
/**
 * Tests the lifetime of a wakelock that times out and is <i>then</i> released.
 *
 * <pre>
 *   t = 000 001 051 101 151 201
 *   A =       [.......]
 * </pre>
 */
@Test
public void testWakelockNonReferenceCountedTimeoutAndReleases() throws Exception {
  ShadowSystemClock.setUptimeMillis(1);

  WakeLockMetrics metricsA = new WakeLockMetrics(true);

  PowerManager.WakeLock wakelock = mPowerManager.newWakeLock(0, "tag");
  mCollector.newWakeLock(wakelock, 0, "tag");

  wakelock.setReferenceCounted(false);
  mCollector.setReferenceCounted(wakelock, false);

  wakelock.acquire(100);
  mCollector.acquire(wakelock, 100);

  ShadowSystemClock.setUptimeMillis(51);
  assertThat(mCollector.getSnapshot(metricsA)).isTrue();
  assertThat(metricsA.acquiredCount).isEqualTo(1);
  assertThat(metricsA.heldTimeMs).isEqualTo(50);
  assertThat(metricsA.tagTimeMs.size()).isEqualTo(1);
  assertThat(metricsA.tagTimeMs.get("tag")).isEqualTo(50);

  ShadowSystemClock.setUptimeMillis(151);
  assertThat(mCollector.getSnapshot(metricsA)).isTrue();
  assertThat(metricsA.acquiredCount).isEqualTo(1);
  assertThat(metricsA.heldTimeMs).isEqualTo(100);
  assertThat(metricsA.tagTimeMs.size()).isEqualTo(1);
  assertThat(metricsA.tagTimeMs.get("tag")).isEqualTo(100);

  ShadowSystemClock.setUptimeMillis(201);
  wakelock.release();
  mCollector.release(wakelock, -1);
  WakeLockMetrics metricsB = new WakeLockMetrics(true);
  assertThat(mCollector.getSnapshot(metricsB)).isTrue();
  assertThat(metricsB).isEqualTo(metricsA);
}
 
Example 9
Source File: WakeLockMetricsCollectorTest.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Test
public void testUnattributedSnapshot() {
  WakeLockMetrics metrics = new WakeLockMetrics();

  PowerManager.WakeLock wakelockA = mPowerManager.newWakeLock(0, "testA");
  mCollector.newWakeLock(wakelockA, 0, "testA");

  mCollector.getSnapshot(metrics);
  assertThat(metrics.heldTimeMs).as("Held time at beginning").isEqualTo(0);

  ShadowSystemClock.setUptimeMillis(1);
  mCollector.acquire(wakelockA, -1);

  ShadowSystemClock.setUptimeMillis(61);
  mCollector.getSnapshot(metrics);
  assertThat(metrics.heldTimeMs).as("Intermediate held time").isEqualTo(60);

  ShadowSystemClock.setUptimeMillis(91);
  mCollector.release(wakelockA, 0);

  mCollector.getSnapshot(metrics);
  assertThat(metrics.heldTimeMs).as("Held time at release").isEqualTo(90);

  ShadowSystemClock.setUptimeMillis(121);
  mCollector.getSnapshot(metrics);
  assertThat(metrics.heldTimeMs).as("Final held time").isEqualTo(90);
}
 
Example 10
Source File: WifiCollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    final PowerManager.WakeLock wl = JoH.getWakeLock("xdrip-wificolsvc-onStart", 60000);

    if (requested_wake_time > 0) {
        JoH.persistentBuggySamsungCheck();
        final long wakeup_jitter = JoH.msSince(requested_wake_time);
        if (wakeup_jitter > 2000) {
            Log.d(TAG, "Wake up jitter: " + JoH.niceTimeScalar(wakeup_jitter));
        }
        if ((wakeup_jitter > TOLERABLE_JITTER) && (!JoH.buggy_samsung) && (JoH.isSamsung())) {
            UserError.Log.wtf(TAG, "Enabled Buggy Samsung workaround due to jitter of: " + JoH.niceTimeScalar(wakeup_jitter));
            JoH.setBuggySamsungEnabled();
            max_wakeup_jitter = 0;
        } else {
            max_wakeup_jitter = Math.max(max_wakeup_jitter, wakeup_jitter);
        }
    }

    if (DexCollectionType.hasWifi()) {
        runWixelReader();
        // For simplicity done here, would better happen once we know if we have a packet or not...
        setFailoverTimer();
    } else {
        lastState = "Stopping " + JoH.hourMinuteString();
        stopSelf();
        if (wl.isHeld()) wl.release();
        return START_NOT_STICKY;
    }
    lastState = "Started " + JoH.hourMinuteString();
    if (wl.isHeld()) wl.release();
    return START_STICKY;
}
 
Example 11
Source File: JoH.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void releaseWakeLock(PowerManager.WakeLock wl) {
    if (debug_wakelocks) Log.d(TAG, "releaseWakeLock: " + wl.toString());
    if (wl == null) return;
    if (wl.isHeld()) {
        try {
            wl.release();
        } catch (Exception e) {
            Log.e(TAG, "Error releasing wakelock: " + e);
        }
    }
}
 
Example 12
Source File: CircleWatchface.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "MyWakelockTag");
    wakeLock.acquire(30000);

    DataMap dataMap = DataMap.fromBundle(intent.getBundleExtra("data"));
    setSgvLevel((int) dataMap.getLong("sgvLevel"));
    Log.d("CircleWatchface", "sgv level : " + getSgvLevel());
    setSgvString(dataMap.getString("sgvString"));
    Log.d("CircleWatchface", "sgv string : " + getSgvString());
    setRawString(dataMap.getString("rawString"));
    setDelta(dataMap.getString("delta"));
    setDatetime(dataMap.getDouble("timestamp"));
    addToWatchSet(dataMap);


    //start animation?
    // dataMap.getDataMapArrayList("entries") == null -> not on "resend data".
    if (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (getSgvString().equals("100") || getSgvString().equals("5.5") || getSgvString().equals("5,5"))) {
        startAnimation();
    }

    prepareLayout();
    prepareDrawTime();
    invalidate();
    wakeLock.release();
}
 
Example 13
Source File: WakeLock.java    From AlarmOn with Apache License 2.0 5 votes vote down vote up
public static void assertNoneHeld() throws WakeLockException {
  for (PowerManager.WakeLock wakeLock : wakeLocks.values()) {
    if (wakeLock.isHeld()) {
      throw new WakeLockException("No wake locks are held.");
    }
  }
}
 
Example 14
Source File: DebugViewContainer.java    From u2020-mvp with Apache License 2.0 5 votes vote down vote up
/**
 * Show the activity over the lock-screen and wake up the device. If you launched the app manually
 * both of these conditions are already true. If you deployed from the IDE, however, this will
 * save you from hundreds of power button presses and pattern swiping per day!
 */
public static void riseAndShine(Activity activity) {
    activity.getWindow().addFlags(FLAG_SHOW_WHEN_LOCKED);

    PowerManager power = (PowerManager) activity.getSystemService(POWER_SERVICE);
    PowerManager.WakeLock lock =
            power.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, "wakeup!");
    lock.acquire();
    lock.release();
}
 
Example 15
Source File: WakeLockUtils.java    From zone-sdk with MIT License 4 votes vote down vote up
public void setWakeLock(PowerManager.WakeLock wakeLock) {
    this.wakeLock = wakeLock;
}
 
Example 16
Source File: BackgroundMessageRetriever.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return False if the retrieval failed and should be rescheduled, otherwise true.
 */
@WorkerThread
public boolean retrieveMessages(@NonNull Context context, MessageRetrievalStrategy... strategies) {
  if (shouldIgnoreFetch(context)) {
    Log.i(TAG, "Skipping retrieval -- app is in the foreground.");
    return true;
  }

  if (!ACTIVE_LOCK.tryAcquire()) {
    Log.i(TAG, "Skipping retrieval -- there's already one enqueued.");
    return true;
  }

  synchronized (this) {
    PowerManager.WakeLock wakeLock = null;

    try {
      wakeLock = WakeLockUtil.acquire(context, PowerManager.PARTIAL_WAKE_LOCK, TimeUnit.SECONDS.toMillis(60), WAKE_LOCK_TAG);

      TextSecurePreferences.setNeedsMessagePull(context, true);

      long         startTime    = System.currentTimeMillis();
      PowerManager powerManager = ServiceUtil.getPowerManager(context);
      boolean      doze         = PowerManagerCompat.isDeviceIdleMode(powerManager);
      boolean      network      = new NetworkConstraint.Factory(ApplicationContext.getInstance(context)).create().isMet();

      if (doze || !network) {
        Log.w(TAG, "We may be operating in a constrained environment. Doze: " + doze + " Network: " + network);
      }

      if (ApplicationDependencies.getInitialMessageRetriever().isCaughtUp()) {
        Log.i(TAG, "Performing normal message fetch.");
        return executeBackgroundRetrieval(context, startTime, strategies);
      } else {
        Log.i(TAG, "Performing initial message fetch.");
        InitialMessageRetriever.Result result = ApplicationDependencies.getInitialMessageRetriever().begin(CATCHUP_TIMEOUT);
        if (result == InitialMessageRetriever.Result.SUCCESS) {
          Log.i(TAG, "Initial message request was completed successfully. " + logSuffix(startTime));
          TextSecurePreferences.setNeedsMessagePull(context, false);
          return true;
        } else {
          Log.w(TAG, "Initial message fetch returned result " + result + ", so doing a normal message fetch.");
          return executeBackgroundRetrieval(context, System.currentTimeMillis(), strategies);
        }
      }
    } finally {
      WakeLockUtil.release(wakeLock, WAKE_LOCK_TAG);
      ACTIVE_LOCK.release();
    }
  }
}
 
Example 17
Source File: InPenService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    final PowerManager.WakeLock wl = JoH.getWakeLock("inpen service", 60000);
    try {
        InPenEntry.started_at = JoH.tsl();
        UserError.Log.d(TAG, "WAKE UP WAKE UP WAKE UP");
        if (shouldServiceRun()) {

            final String mac = InPen.getMac(); // load from settings class
            if (emptyString(mac)) {
                // if mac not set then start up a scan and do nothing else
                new FindNearby().scan();
            } else {

                setAddress(mac);
                commonServiceStart();
                if (intent != null) {
                    final String function = intent.getStringExtra("function");
                    if (function != null) {
                        switch (function) {

                            case "failover":
                                changeState(CLOSE);
                                break;
                            case "reset":
                                JoH.static_toast_long("Searching for Pen");
                                InPen.setMac("");
                                InPenEntry.startWithRefresh();
                                break;
                            case "refresh":
                                currentPenAttachTime = null;
                                currentPenTime = null;
                                changeState(INIT);
                                break;
                            case "prototype":
                                //     changeState(PROTOTYPE);
                                break;
                        }
                    }
                }
            }
            setFailOverTimer();
            return START_STICKY;
        } else {
            UserError.Log.d(TAG, "Service is NOT set be active - shutting down");
            stopSelf();
            return START_NOT_STICKY;
        }
    } finally {
        JoH.releaseWakeLock(wl);
    }
}
 
Example 18
Source File: MedtrumCollectionService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public synchronized boolean automata() {

        if ((last_automata_state != state) || (JoH.ratelimit("jam-g5-dupe-auto", 2))) {
            last_automata_state = state;
            final PowerManager.WakeLock wl = JoH.getWakeLock("jam-g5-automata", 60000);
            try {
                switch (state) {

                    case INIT:
                        initialize();
                        break;
                    case SCAN:
                        scan_for_device();
                        break;
                    case CONNECT:
                        connect_to_device();
                        break;
                    case ENABLE:
                        retry_backoff = 0; // we have a connection
                        enable_features_and_listen();
                        break;
                    case DISCOVER:
                        changeState(state.next());
                        break;
                    case CALIBRATE:
                        check_calibrate();
                        break;
                    case GET_DATA:
                        get_data();
                        break;
                    case SET_TIME:
                        if (JoH.pratelimit("medtrum-set-time-" + serial, 60)) {
                            sendTx(new TimeTx());
                        } else {
                            changeState(state.next());
                        }
                        break;
                    case SET_CONN_PARAM:
                        sendTx(new ConnParamTx());
                        break;
                    case CLOSE:
                        //prepareToWakeup(); // TODO this skips service wake up
                        stopConnect();
                        setRetryTimer();
                        state = CLOSED;
                        //changeState(INIT);
                        break;
                    case CLOSED:
                        setRetryTimer();
                        break;
                    case LISTEN:
                        status("Listening");
                        if (notificationSubscription == null || notificationSubscription.isUnsubscribed()) {
                            changeState(SCAN);
                        }
                        break;

                }
            } finally {
                JoH.releaseWakeLock(wl);
            }
        } else {
            UserError.Log.d(TAG, "Ignoring duplicate automata state within 2 seconds: " + state);
        }
        return true;
    }
 
Example 19
Source File: InPenService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    final PowerManager.WakeLock wl = JoH.getWakeLock("inpen service", 60000);
    try {
        InPenEntry.started_at = JoH.tsl();
        UserError.Log.d(TAG, "WAKE UP WAKE UP WAKE UP");
        if (shouldServiceRun()) {

            final String mac = InPen.getMac(); // load from settings class
            if (emptyString(mac)) {
                // if mac not set then start up a scan and do nothing else
                new FindNearby().scan();
            } else {

                setAddress(mac);
                commonServiceStart();
                if (intent != null) {
                    final String function = intent.getStringExtra("function");
                    if (function != null) {
                        switch (function) {

                            case "failover":
                                changeState(CLOSE);
                                break;
                            case "reset":
                                JoH.static_toast_long("Searching for Pen");
                                InPen.setMac("");
                                InPenEntry.startWithRefresh();
                                break;
                            case "refresh":
                                currentPenAttachTime = null;
                                currentPenTime = null;
                                changeState(INIT);
                                break;
                            case "prototype":
                                //     changeState(PROTOTYPE);
                                break;
                        }
                    }
                }
            }
            setFailOverTimer();
            return START_STICKY;
        } else {
            UserError.Log.d(TAG, "Service is NOT set be active - shutting down");
            stopSelf();
            return START_NOT_STICKY;
        }
    } finally {
        JoH.releaseWakeLock(wl);
    }
}
 
Example 20
Source File: Ob1G5StateMachine.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@SuppressLint("CheckResult")
public synchronized static boolean doKeepAliveAndBondRequest(Ob1G5CollectionService parent, RxBleConnection connection) {

    if (connection == null) return false;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UserError.Log.d(TAG, "Requesting high priority");
        connection.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH, 500, TimeUnit.MILLISECONDS);
    }
    UserError.Log.e(TAG, "Sending keepalive..");
    connection.writeCharacteristic(Authentication, nn(new KeepAliveTxMessage(60).byteSequence))
            .subscribe(
                    characteristicValue -> {
                        UserError.Log.d(TAG, "Wrote keep-alive request successfully");
                        speakSlowly(); // is this really needed here?
                        parent.unBond();
                        parent.instantCreateBondIfAllowed();
                        speakSlowly();
                        connection.writeCharacteristic(Authentication, nn(new BondRequestTxMessage().byteSequence))
                                .subscribe(
                                        bondRequestValue -> {
                                            UserError.Log.d(TAG, "Wrote bond request value: " + JoH.bytesToHex(bondRequestValue));
                                            speakSlowly();
                                            connection.readCharacteristic(Authentication)
                                                    .observeOn(Schedulers.io())
                                                    .timeout(10, TimeUnit.SECONDS)
                                                    .subscribe(
                                                            status_value -> {
                                                                UserError.Log.d(TAG, "Got status read after keepalive " + JoH.bytesToHex(status_value));
                                                                authenticationProcessor(parent, connection, status_value);
                                                                throw new OperationSuccess("Bond requested");
                                                            }, throwable -> {
                                                                UserError.Log.e(TAG, "Throwable when reading characteristic after keepalive: " + throwable);
                                                            });

                                            // Wrote bond request successfully was here moved above - is this right?
                                        }, throwable -> {
                                            // failed to write bond request retry?
                                            if (!(throwable instanceof OperationSuccess)) {
                                                UserError.Log.e(TAG, "Failed to write bond request! " + throwable);
                                            }
                                        });

                    }, throwable -> {
                        // Could not write keep alive ? retry?
                        UserError.Log.e(TAG, "Failed writing keep-alive request! " + throwable);
                    });
    UserError.Log.d(TAG, "Exiting doKeepAliveBondRequest");
    final PowerManager.WakeLock linger = JoH.getWakeLock("jam-g5-bond-linger", 30000);
    return true;
}