android.os.PowerManager.WakeLock Java Examples

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: WakeLockUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param tag will be prefixed with "signal:" if it does not already start with it.
 */
public static WakeLock acquire(@NonNull Context context, int lockType, long timeout, @NonNull String tag) {
  tag = prefixTag(tag);
  try {
    PowerManager powerManager = ServiceUtil.getPowerManager(context);
    WakeLock     wakeLock     = powerManager.newWakeLock(lockType, tag);

    wakeLock.acquire(timeout);
    Log.d(TAG, "Acquired wakelock with tag: " + tag);

    return wakeLock;
  } catch (Exception e) {
    Log.w(TAG, "Failed to acquire wakelock with tag: " + tag, e);
    return null;
  }
}
 
Example #2
Source File: StepService.java    From Running with Apache License 2.0 6 votes vote down vote up
synchronized private WakeLock getLock(Context context) {
    if (mWakeLock != null) {
        if (mWakeLock.isHeld())
            mWakeLock.release();
        mWakeLock = null;
    }

    if (mWakeLock == null) {
        PowerManager mgr = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                StepService.class.getName());
        mWakeLock.setReferenceCounted(true);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if (hour >= 23 || hour <= 6) {
            mWakeLock.acquire(5000);
        } else {
            mWakeLock.acquire(300000);
        }
    }

    return (mWakeLock);
}
 
Example #3
Source File: CollectorService.java    From TowerCollector with Mozilla Public License 2.0 6 votes vote down vote up
private void registerWakeLockAcquirer() {
    if (keepScreenOnMode == KeepScreenOnMode.Disabled) {
        Timber.d("registerWakeLockAcquirer(): WakeLock not configured");
        return;
    }
    periodicalWakeLockAcquirer = new Timer();
    // run scheduled cell listener
    periodicalWakeLockAcquirer.schedule(new TimerTask() {
        private final String INNER_TAG = CollectorService.class.getSimpleName() + ".Periodical" + WakeLock.class.getSimpleName() + "Acquirer";

        @Override
        public void run() {
            synchronized (reacquireWakeLockLock) {
                WakeLock oldWakeLock = wakeLock;
                Timber.tag(INNER_TAG).d("run(): New WakeLock acquire");
                wakeLock = createWakeLock(keepScreenOnMode);
                wakeLock.acquire(WAKE_LOCK_TIMEOUT);
                Timber.tag(INNER_TAG).d("run(): Old WakeLock release");
                if (oldWakeLock != null && oldWakeLock.isHeld())
                    oldWakeLock.release();
            }
        }
    }, 0, WAKE_LOCK_ACQUIRE_INTERVAL);
}
 
Example #4
Source File: ScreenLockUtil.java    From AndroidModulePattern with Apache License 2.0 6 votes vote down vote up
/**
 * 保持屏幕常亮
 *
 * @param activity you know
 */
public static void keepScreenOn(Activity activity) {
    WakeLock wakeLock = mWakeLockArray.get(activity);
    if (wakeLock == null) {
        PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                activity.getClass().getName());
    }

    if (!wakeLock.isHeld()) {
        wakeLock.acquire();
    }

    mWakeLockArray.put(activity, wakeLock);

    cancelLockScreen(activity);

    Log.i(TAG, "开启屏幕常亮");
}
 
Example #5
Source File: MqttService.java    From Sparkplug with Eclipse Public License 1.0 6 votes vote down vote up
@Override
      @SuppressLint("Wakelock")
public void onReceive(Context context, Intent intent) {
	traceDebug(TAG, "Internal network status receive.");
	// we protect against the phone switching off
	// by requesting a wake lock - we request the minimum possible wake
	// lock - just enough to keep the CPU running until we've finished
	PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
	WakeLock wl = pm
			.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
	wl.acquire();
	traceDebug(TAG,"Reconnect for Network recovery.");
	if (isOnline()) {
		traceDebug(TAG,"Online,reconnect.");
		// we have an internet connection - have another try at
		// connecting
		reconnect();
	} else {
		notifyClientsOffline();
	}

	wl.release();
}
 
Example #6
Source File: WakefulBroadcastReceiver.java    From letv with Apache License 2.0 6 votes vote down vote up
public static boolean completeWakefulIntent(Intent intent) {
    int id = intent.getIntExtra(EXTRA_WAKE_LOCK_ID, 0);
    if (id == 0) {
        return false;
    }
    synchronized (mActiveWakeLocks) {
        WakeLock wl = (WakeLock) mActiveWakeLocks.get(id);
        if (wl != null) {
            wl.release();
            mActiveWakeLocks.remove(id);
            return true;
        }
        Log.w("WakefulBroadcastReceiver", "No active wake lock id #" + id);
        return true;
    }
}
 
Example #7
Source File: WakefulBroadcastReceiver.java    From letv with Apache License 2.0 6 votes vote down vote up
public static ComponentName startWakefulService(Context context, Intent intent) {
    ComponentName comp;
    synchronized (mActiveWakeLocks) {
        int id = mNextId;
        mNextId++;
        if (mNextId <= 0) {
            mNextId = 1;
        }
        intent.putExtra(EXTRA_WAKE_LOCK_ID, id);
        comp = context.startService(intent);
        if (comp == null) {
            comp = null;
        } else {
            WakeLock wl = ((PowerManager) context.getSystemService("power")).newWakeLock(1, "wake:" + comp.flattenToShortString());
            wl.setReferenceCounted(false);
            wl.acquire(60000);
            mActiveWakeLocks.put(id, wl);
        }
    }
    return comp;
}
 
Example #8
Source File: ApplicationMigrationService.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
  notification              = initializeBackgroundNotification();
  PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
  WakeLock     wakeLock     = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Migration");

  try {
    wakeLock.acquire();

    setState(new ImportState(ImportState.STATE_MIGRATING_BEGIN, null));

    SmsMigrator.migrateDatabase(ApplicationMigrationService.this,
                                masterSecret,
                                ApplicationMigrationService.this);

    setState(new ImportState(ImportState.STATE_MIGRATING_COMPLETE, null));

    setDatabaseImported(ApplicationMigrationService.this);
    stopForeground(true);
    notifyImportComplete();
    stopSelf();
  } finally {
    wakeLock.release();
  }
}
 
Example #9
Source File: WakeLockManager.java    From OmniList with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Releases a partial {@link WakeLock} with a tag contained in the given{@link Intent}
 *
 * @param intent intent*/
private void releasePartialWakeLock(Intent intent) {
    if (intent.hasExtra(WakeLockManager.EXTRA_WAKELOCK_TAG)) {
        final int hash = intent.getIntExtra(WakeLockManager.EXTRA_WAKELOCK_HASH, -1);
        final String tag = intent.getStringExtra(WakeLockManager.EXTRA_WAKELOCK_TAG);
        // We use copy on write list. Iterator won't cause ConcurrentModificationException
        for (WakeLock wakeLock : wakeLocks) {
            if (hash == wakeLock.hashCode()) {
                if (wakeLock.isHeld()) {
                    wakeLock.release();
                    LogUtils.d("releasePartialWakeLock: " + wakeLock.toString() + " " + tag + " was released");
                } else {
                    LogUtils.d("releasePartialWakeLock: " + wakeLock.toString() + " " + tag + " was already released!");
                }
                wakeLocks.remove(wakeLock);
                return;
            }
        }
        LogUtils.e("releasePartialWakeLock: " + "Hash " + hash + " was not found");
    }
}
 
Example #10
Source File: WakeLockUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param tag will be prefixed with "signal:" if it does not already start with it.
 */
public static void release(@Nullable WakeLock wakeLock, @NonNull String tag) {
  tag = prefixTag(tag);
  try {
    if (wakeLock == null) {
      Log.d(TAG, "Wakelock was null. Skipping. Tag: " + tag);
    } else if (wakeLock.isHeld()) {
      wakeLock.release();
      Log.d(TAG, "Released wakelock with tag: " + tag);
    } else {
      Log.d(TAG, "Wakelock wasn't held at time of release: " + tag);
    }
  } catch (Exception e) {
    Log.w(TAG, "Failed to release wakelock with tag: " + tag, e);
  }
}
 
Example #11
Source File: PirateBoxService.java    From AndroidPirateBox with MIT License 5 votes vote down vote up
@Override
public WakeLock getWakeLock() {
	PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
			Constants.TAG);
	
	return wl;
}
 
Example #12
Source File: OpenSLMediaPlayer.java    From android-openslmediaplayer with Apache License 2.0 5 votes vote down vote up
private void createWakeLockObject(Context context, int mode) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    WakeLock wakelock = pm.newWakeLock(
            mode | PowerManager.ON_AFTER_RELEASE,
            WAKELOCK_TAG);
    wakelock.setReferenceCounted(false);

    mWakeLock = wakelock;
}
 
Example #13
Source File: MQTTService.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context ctx, Intent intent) {
    String action = intent.getAction();
    if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(action)) {
        // we protect against the phone switching off while we're doing this
        // by requesting a wake lock - we request the minimum possible wake
        // lock - just enough to keep the CPU running until we've finished
        PowerManager pm = (PowerManager) _context
                .getSystemService(Service.POWER_SERVICE);
        WakeLock wl = pm
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
        acquireWakelock(wl, "BackgroundDataChange acquire");

        ConnectivityManager cm = (ConnectivityManager) _context
                .getSystemService(Service.CONNECTIVITY_SERVICE);
        if (cm.getBackgroundDataSetting()) {
            // user has allowed background data - we start again - picking
            // up where we left off in handleStart before
            defineConnectionToBroker(brokerHostName);
            // handleStart(intent, 0);
        } else {
            // user has disabled background data
            connectionStatus = MQTTConnectionStatus.NOTCONNECTED_DATADISABLED;

            // update the app to show that the connection has been disabled
            broadcastServiceStatus(NOTCONNECTED_DATADISABLED_DESCRIPTION);

            // disconnect from the broker
            disconnectFromBroker();
        }

        // we're finished - if the phone is switched off, it's okay for the
        // CPU
        // to sleep now
        releaseWakelock(wl, "BackgroundDataChange release");
    }
}
 
Example #14
Source File: WakeLockManager.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Removes any non-held wake locks from {@link #wakeLocks}. Such locks may be present when a
 * wake lock acquired with a timeout is not released before the timeout expires. We only
 * explicitly remove wake locks from the map when {@link #release} is called, so a timeout results
 * in a non-held wake lock in the map.
 * <p>
 * Must be called as the first line of all non-private methods.
 * <p>
 * REQUIRES: caller must hold {@link #LOCK}.
 */
private void cleanup() {
  Iterator<Map.Entry<Object, WakeLock>> wakeLockIter = wakeLocks.entrySet().iterator();

  // Check each map entry.
  while (wakeLockIter.hasNext()) {
    Map.Entry<Object, WakeLock> wakeLockEntry = wakeLockIter.next();
    if (!wakeLockEntry.getValue().isHeld()) {
      // Warn and remove the entry from the map if the lock is not held.
      logger.warning("Found un-held wakelock '%s' -- timed-out?", wakeLockEntry.getKey());
      wakeLockIter.remove();
    }
  }
}
 
Example #15
Source File: MQTTService.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context ctx, Intent intent) {
    String action = intent.getAction();
    if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
        // we protect against the phone switching off while we're doing this
        // by requesting a wake lock - we request the minimum possible wake
        // lock - just enough to keep the CPU running until we've finished
        PowerManager pm = (PowerManager) _context
                .getSystemService(Service.POWER_SERVICE);
        WakeLock wl = pm
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MQTT");
        acquireWakelock(wl, "NetworkConnection acquire");

        if (isOnline()) {
            // we have an internet connection - have another try at
            // connecting
            if (!connectionStatus.equals(MQTTConnectionStatus.CONNECTING)
                    && !connectionStatus.equals(MQTTConnectionStatus.CONNECTED)) {
                connectionStatus = MQTTConnectionStatus.CONNECTING;
                connectToBrokerThread();
            }
            /**网络状态发生变化,tcp连接仍然存在*/
            else if(connectionStatus.equals(MQTTConnectionStatus.CONNECTED))
            {
                Intent mQttPingIntent = new Intent(MQTTService.MQTT_PING_ACTION);
                mQttPingIntent.setPackage(ctx.getPackageName());
                ctx.sendBroadcast(mQttPingIntent);
            }
        }

        // we're finished - if the phone is switched off, it's okay for the
        // CPU
        // to sleep now
        releaseWakelock(wl, "NetworkConnection release");
    }
}
 
Example #16
Source File: WakeLockManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Removes any non-held wake locks from {@link #wakeLocks}. Such locks may be present when a
 * wake lock acquired with a timeout is not released before the timeout expires. We only
 * explicitly remove wake locks from the map when {@link #release} is called, so a timeout results
 * in a non-held wake lock in the map.
 * <p>
 * Must be called as the first line of all non-private methods.
 * <p>
 * REQUIRES: caller must hold {@link #LOCK}.
 */
private void cleanup() {
  Iterator<Map.Entry<Object, WakeLock>> wakeLockIter = wakeLocks.entrySet().iterator();

  // Check each map entry.
  while (wakeLockIter.hasNext()) {
    Map.Entry<Object, WakeLock> wakeLockEntry = wakeLockIter.next();
    if (!wakeLockEntry.getValue().isHeld()) {
      // Warn and remove the entry from the map if the lock is not held.
      logger.warning("Found un-held wakelock '%s' -- timed-out?", wakeLockEntry.getKey());
      wakeLockIter.remove();
    }
  }
}
 
Example #17
Source File: MQTTService.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void acquireWakelock(WakeLock wl, String tag) {
    try {
        wl.acquire();
    } catch (Exception e) {
        PushReportUtility.oe(tag, e);
    }
}
 
Example #18
Source File: MQTTService.java    From appcan-android with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void releaseWakelock(WakeLock wl, String tag) {
    try {
        wl.release();
    } catch (Exception e) {
        PushReportUtility.oe(tag, e);
    }
}
 
Example #19
Source File: Lock.java    From Kernel-Tuner with GNU General Public License v3.0 5 votes vote down vote up
private static PowerManager.WakeLock getLock(Context context) {
	if (lock == null) {
		PowerManager mgr = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);

		lock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "org.jtb.alogcat.lock");
		lock.setReferenceCounted(true);
	}
	return lock;
}
 
Example #20
Source File: Lock.java    From Kernel-Tuner with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized void acquire(Context context) {
	WakeLock wakeLock = getLock(context);
	if (!wakeLock.isHeld()) {
		wakeLock.acquire();
		//Log.d("alogcat", "wake lock acquired");
	}
}
 
Example #21
Source File: DbBindingService.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
protected final void onHandleIntent (final Intent i) {
	final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	final WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, C.TAG);
	wl.acquire();
	try {
		doWork(i);
	}
	finally {
		wl.release();
	}
}
 
Example #22
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 #23
Source File: WakeLockManager.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a wake lock to use for {@code key}. If a lock is already present in the map,
 * returns that lock. Else, creates a new lock, installs it in the map, and returns it.
 * <p>
 * REQUIRES: caller must hold {@link #LOCK}.
 */
private PowerManager.WakeLock getWakeLock(Object key) {
  if (key == null) {
    throw new IllegalArgumentException("Key can not be null");
  }
  PowerManager.WakeLock wakeLock = wakeLocks.get(key);
  if (wakeLock == null) {
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, key.toString());
    wakeLocks.put(key, wakeLock);
  }
  return wakeLock;
}
 
Example #24
Source File: WakeLockManager.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Removes any non-held wake locks from {@link #wakeLocks}. Such locks may be present when a
 * wake lock acquired with a timeout is not released before the timeout expires. We only
 * explicitly remove wake locks from the map when {@link #release} is called, so a timeout results
 * in a non-held wake lock in the map.
 * <p>
 * Must be called as the first line of all non-private methods.
 * <p>
 * REQUIRES: caller must hold {@link #LOCK}.
 */
private void cleanup() {
  Iterator<Map.Entry<Object, WakeLock>> wakeLockIter = wakeLocks.entrySet().iterator();

  // Check each map entry.
  while (wakeLockIter.hasNext()) {
    Map.Entry<Object, WakeLock> wakeLockEntry = wakeLockIter.next();
    if (!wakeLockEntry.getValue().isHeld()) {
      // Warn and remove the entry from the map if the lock is not held.
      logger.warning("Found un-held wakelock '%s' -- timed-out?", wakeLockEntry.getKey());
      wakeLockIter.remove();
    }
  }
}
 
Example #25
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 #26
Source File: WakeLockManager.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a wake lock to use for {@code key}. If a lock is already present in the map,
 * returns that lock. Else, creates a new lock, installs it in the map, and returns it.
 * <p>
 * REQUIRES: caller must hold {@link #LOCK}.
 */
private PowerManager.WakeLock getWakeLock(Object key) {
  if (key == null) {
    throw new IllegalArgumentException("Key can not be null");
  }
  PowerManager.WakeLock wakeLock = wakeLocks.get(key);
  if (wakeLock == null) {
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, key.toString());
    wakeLocks.put(key, wakeLock);
  }
  return wakeLock;
}
 
Example #27
Source File: WakeLockUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Run a runnable with a wake lock. Ensures that the lock is safely acquired and released.
 *
 * @param tag will be prefixed with "signal:" if it does not already start with it.
 */
public static void runWithLock(@NonNull Context context, int lockType, long timeout, @NonNull String tag, @NonNull Runnable task) {
  WakeLock wakeLock = null;
  try {
    wakeLock = acquire(context, lockType, timeout, tag);
    task.run();
  } finally {
    if (wakeLock != null) {
      release(wakeLock, tag);
    }
  }
}
 
Example #28
Source File: WakeLockManager.java    From OmniList with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Acquires a partial {@link WakeLock}, stores it internally and puts the
 * tag into the {@link Intent}. To be used with {@link WakeLockManager#releasePartialWakeLock(Intent)}
 *
 * @param intent intent
 * @param wlTag tag */
public void acquirePartialWakeLock(Intent intent, String wlTag) {
    final WakeLock wl = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wlTag);
    wl.acquire();
    wakeLocks.add(wl);
    intent.putExtra(WakeLockManager.EXTRA_WAKELOCK_HASH, wl.hashCode());
    intent.putExtra(WakeLockManager.EXTRA_WAKELOCK_TAG, wlTag);
    LogUtils.d("acquirePartialWakeLock: " + wl.toString() + " " + wlTag + " was acquired");
}
 
Example #29
Source File: WakeLockManager.java    From 365browser with Apache License 2.0 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 #30
Source File: MediaButtonReceiver.java    From media-button-router with Apache License 2.0 5 votes vote down vote up
/**
 * Shows the selector dialog that allows the user to decide which music
 * player should receiver the media button press intent.
 * 
 * @param context
 *            The context.
 * @param intent
 *            The intent to forward.
 * @param keyEvent
 *            The key event
 */
private void showSelector(Context context, Intent intent, KeyEvent keyEvent) {
    KeyguardManager manager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    boolean locked = manager.inKeyguardRestrictedInputMode();

    Intent showForwardView = new Intent(Constants.INTENT_ACTION_VIEW_MEDIA_BUTTON_LIST);
    showForwardView.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    showForwardView.putExtras(intent);
    showForwardView.setClassName(context,
            locked ? ReceiverSelectorLocked.class.getName() : ReceiverSelector.class.getName());

    /* COMMENTED OUT FOR MARKET RELEASE Log.i(TAG, "Media Button Receiver: starting selector activity for keyevent: " + keyEvent); */

    if (locked) {

        // XXX See if this actually makes a difference, might
        // not be needed if we move more things to onCreate?
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        // acquire temp wake lock
        WakeLock wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
        wakeLock.setReferenceCounted(false);

        // Our app better display within 3 seconds or we have
        // bigger issues.
        wakeLock.acquire(3000);
    }
    context.startActivity(showForwardView);
}