赞
踩
应用在涉及音视频播放功能时可能需要点亮屏幕,此文把点亮屏幕相关工具类和使用类的代码贴出来,若有问题欢迎指正!
工具类:WakeLockUtil,相关代码如下:
- public class WakeLockUtil {
-
- /**
- * 点亮屏幕
- *
- * @param timeout The timeout after which to release the wake lock, in milliseconds.
- */
- @Nullable
- public static PowerManager.WakeLock acquireWakeLock(@NonNull Context context, long timeout) {
- PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
- if (pm == null)
- return null;
- PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
- PowerManager.FULL_WAKE_LOCK |
- PowerManager.ON_AFTER_RELEASE,
- context.getClass().getName());
- wakeLock.acquire(timeout);
- return wakeLock;
- }
-
- public static void release(@Nullable PowerManager.WakeLock wakeLock) {
- if (wakeLock != null && wakeLock.isHeld()) {
- wakeLock.release();
- }
- }
- }
使用类:WakeLockActivity,相关代码如下:
- public class WakeLockActivity extends AppCompatActivity {
- private PowerManager.WakeLock mWakeLock;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //点亮屏幕2分钟,2分钟后此方法会自动释放PowerManager.WakeLock
- mWakeLock = WakeLockUtil.acquireWakeLock(this, 2 * 60 * 1000);
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- WakeLockUtil.release(mWakeLock);
- }
- }
相关权限如下:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。