下面列出了怎么用android.os.PowerManager.WakeLock的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @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;
}
}
/**
* @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);
}
}
/**
* 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");
}
}
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;
}
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;
}
}
/**
* 保持屏幕常亮
*
* @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, "开启屏幕常亮");
}
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);
}
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);
}
@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();
}
@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();
}
}
/**
* 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);
}
}
}
/**
* 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");
}
private boolean _acquireWakeLock(WakeLock lock, long timeout) {
synchronized (lock) {
if (!lock.isHeld()) {
if (timeout > 0) {
lock.acquire(timeout);
} else {
lock.acquire();
}
return true;
}
}
return false;
}
private boolean _releaseWakeLock(WakeLock lock) {
synchronized (lock) {
if (lock.isHeld()) {
lock.release();
return true;
}
}
return false;
}
/**
* 取消屏幕常亮
*
* @param activity you know
*/
public static void cancelKeepScreen(Activity activity) {
WakeLock wakeLock = mWakeLockArray.get(activity);
if (wakeLock != null) {
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
Log.i(TAG, "取消屏幕常亮");
}
private boolean _acquireWakeLock(WakeLock lock, long timeout) {
synchronized (lock) {
if (!lock.isHeld()) {
if (timeout > 0) {
lock.acquire(timeout);
} else {
lock.acquire();
}
return true;
}
}
return false;
}
private boolean _releaseWakeLock(WakeLock lock) {
synchronized (lock) {
if (lock.isHeld()) {
lock.release();
return true;
}
}
return false;
}
@Override
protected String doInBackground(String... params) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
final WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, "");
wl.acquire();
return "Executed";
}
private WakeLock createWakeLock(KeepScreenOnMode keepScreenOnMode) {
WakeLock newWakeLock = null;
if (keepScreenOnMode == KeepScreenOnMode.FullBrightness) {
newWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, SERVICE_FULL_NAME + ".BrightWakeLock_" + System.currentTimeMillis());
newWakeLock.setReferenceCounted(false);
} else if (keepScreenOnMode == KeepScreenOnMode.Dimmed) {
newWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, SERVICE_FULL_NAME + ".DimWakeLock_" + System.currentTimeMillis());
newWakeLock.setReferenceCounted(false);
}
return newWakeLock;
}
@SuppressLint("Wakelock") @Override
protected String doInBackground(String... params) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
final WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, "");
wl.acquire();
return "Executed";
}
/**
* 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);
}
/**
* 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");
}
}
}
/**
* 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;
}
/**
* 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();
}
}
}
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;
}
@Override
public WakeLock getWakeLock() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
Constants.TAG);
return wl;
}
@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");
}
}
@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");
}
}
private void acquireWakelock(WakeLock wl, String tag) {
try {
wl.acquire();
} catch (Exception e) {
PushReportUtility.oe(tag, e);
}
}
private void releaseWakelock(WakeLock wl, String tag) {
try {
wl.release();
} catch (Exception e) {
PushReportUtility.oe(tag, e);
}
}