In my previous post, I discussed the pros and cons of the various means of keeping the screen alive in Android, focusing mainly on the need for sandbox permissions in your application’sAndroidManifest.xmlfile.

In this post, I’d like to further elaborate on the “shortcut” techniques to allow you to keep the screen alive, without explicitly managing a Wake Lock in your application.

FLAG_KEEP_SCREEN_ON

I’ve already covered the technique of setting a flag on your Activity’s main window to keep the screen active:

getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );

There are two things to keep in mind with this approach:

  1. FLAG_KEEP_SCREEN_ONonly works when the app window is onscreen. If the user switches apps, Android automatically releases the wake lock. That might be fine for your use case, but if you have a long-running background task that really needs to keep the device running until finished, this isn’t an airtight approach.
  2. FLAG_KEEP_SCREEN_ONdoes just that; it keeps the screen active along with the rest of the device. If you directly create and manage a raw wake lock in your own code, you have more granularity, for example allowing the screen to go dim or go off completely whilst still allowing the CPU to do its thing.

I won’t discuss how to create and manage a Wake Lock directly; instead, I’ll refer you to the SDK docs and to a short code example (I happen to like the anddev.org site for its nice, short and useful code snippets).

android:keepScreenOn

Although I haven’t tried this in my own dev work, you can also enforce “screen always on” behavior on a per-view basis.

Every view has an android:keepScreenOnattribute that you can use to keep the screen active whenever the view is visible. This should be as easy as simply setting the attribute in the XML layout you use to define your views, plus it needs no Java code at all.

I suspectandroid:keepScreenOnworks by setting theFLAG_KEEP_SCREEN_ONon the window for you whenever the view is visible to the user. Anyway, this is handy to use if your need to keep the screen active is associated with a particular view in your app.


更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. 2014.7.23 cocos2d-x3.2到android的联调
  2. Android(安卓)开发入门-活动的基本用法
  3. android 中 Timer 的使用及源码分析
  4. Ubuntu系统下Android4.0源码开发多寄存器
  5. Android(安卓)webview加载本地html实现跨
  6. Android(安卓)ViewFlipper 用例
  7. Failure [INSTALL_FAILED_OLDER_SDK]
  8. Android(安卓)TextView控件
  9. ORMLite简介和增删改查方法的使用
  10. Android(安卓)Ble蓝牙开发内存泄漏