Android-讓設備保持喚醒(激活)狀態(tài)

Keeping the Device Awake

To avoid draining the battery, an Android device that is left idle quickly falls asleep. However, there are times when an application needs to wake up the screen or the CPU and keep it awake to complete some work.

The approach you take depends on the needs of your app. However, a general rule of thumb is that you should use the most lightweight approach possible for your app, to minimize your app's impact on system resources. The following sections describe how to handle the cases where the device's default sleep behavior is incompatible with the requirements of your app.

為了避免電池尿崩,Android會在沒有任務的時候快速進入睡眠狀態(tài)硫朦。然而有時候應用需要保持激活狀態(tài)哲思。

你的需求決定了你選擇的方法。一般來說,盡可能選擇盡量輕量的方法滿足你的需求井赌。下面幾個選項講述了如何選擇這些方法喷屋。

Keep the Screen On

Certain apps need to keep the screen turned on, such as games or movie apps. The best way to do this is to use the FLAG_KEEP_SCREEN_ON in your activity (and only in an activity, never in a service or other app component). For example:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

The advantage of this approach is that unlike wake locks (discussed in
Keep the CPU On), it doesn't require special permission, and the platform correctly manages the user moving between applications, without your app needing to worry about releasing unused resources.
Another way to implement this is in your application's layout XML file, by using the android:keepScreenOn

attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Usingandroid:keepScreenOn="true" is equivalent to using FLAG_KEEP_SCREEN_ON. You can use whichever approach is best for your app. The advantage of setting the flag programmatically in your activity is that it gives you the option of programmatically clearing the flag later and thereby allowing the screen to turn off.

Note:You don't need to clear theFLAG_KEEP_SCREEN_ONflag unless you no longer want the screen to stay on in your running application (for example, if you want the screen to time out after a certain period of inactivity). The window manager takes care of ensuring that the right things happen when the app goes into the background or returns to the foreground. But if you want to explicitly clear the flag and thereby allow the screen to turn off again, useclearFlags():getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).

簡而言之,通過設置FLAG_KEEP_SCREEN_ON標記來是屏幕保持常亮寸齐,這是一種比較輕量級的方法,系統(tǒng)會根據(jù)App是否在前臺決定這個設置是否生效抄谐,如果是一般閱讀類App渺鹦,電影App推薦使用這個。

Keep the CPU On

If you need to keep the CPU running in order to complete some work before the device goes to sleep, you can use aPowerManagersystem service feature called wake locks. Wake locks allow your application to control the power state of the host device.
Creating and holding wake locks can have a dramatic impact on the host device's battery life. Thus you should use wake locks only when strictly necessary and hold them for as short a time as possible. For example, you should never need to use a wake lock in an activity. As described above, if you want to keep the screen on in your activity, useFLAG_KEEP_SCREEN_ON.
One legitimate case for using a wake lock might be a background service that needs to grab a wake lock to keep the CPU running to do work while the screen is off. Again, though, this practice should be minimized because of its impact on battery life.
To use a wake lock, the first step is to add theWAKE_LOCKpermission to your application's manifest file:

<uses-permission android:name="android.permission.WAKE_LOCK" />

If your app includes a broadcast receiver that uses a service to do some work, you can manage your wake lock through aWakefulBroadcastReceiver, as described inUsing a WakefulBroadcastReceiver. This is the preferred approach. If your app doesn't follow that pattern, here is how you set a wake lock directly:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyWakelockTag");
wakeLock.acquire();

To release the wake lock, callwakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Using WakefulBroadcastReceiver

Using a broadcast receiver in conjunction with a service lets you manage the life cycle of a background task.AWakefulBroadcastReceiveris a special type of broadcast receiver that takes care of creating and managing aPARTIAL_WAKE_LOCKfor your app. AWakefulBroadcastReceiverpasses off the work to aService(typically anIntentService), while ensuring that the device does not go back to sleep in the transition. If you don't hold a wake lock while transitioning the work to a service, you are effectively allowing the device to go back to sleep before the work completes. The net result is that the app might not finish doing the work until some arbitrary point in the future, which is not what you want.
The first step in using aWakefulBroadcastReceiveris to add it to your manifest, as with any other broadcast receiver:

<receiver android:name=".MyWakefulReceiver"></receiver>

The following code starts MyIntentService with the method startWakefulService(). This method is comparable tostartService(), except that theWakefulBroadcastReceiveris holding a wake lock when the service starts. The intent that is passed withstartWakefulService()holds an extra identifying the wake lock:

public class MyWakefulReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Start the service, keeping the device awake while the service is
        // launching. This is the Intent to deliver to the service.
        Intent service = new Intent(context, MyIntentService.class);
        startWakefulService(context, service);
    }
}

When the service is finished, it callsMyWakefulReceiver.completeWakefulIntent()to release the wake lock. ThecompleteWakefulIntent()method has as its parameter the same intent that was passed in from theWakefulBroadcastReceiver:

public class MyIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    public MyIntentService() {
        super("MyIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        // Do the work that requires your app to keep the CPU running.
        // ...
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        MyWakefulReceiver.completeWakefulIntent(intent);
    }
}

使用WAKE_LOCK保持CPU運算蛹含,但是一般不推薦使用毅厚,除非你有非要完成的任務。絕對不要在Activity中使用挣惰,一般在Service中使用即可卧斟。具體使用方法已經很清楚了,不譯了憎茂。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末珍语,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子竖幔,更是在濱河造成了極大的恐慌板乙,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拳氢,死亡現(xiàn)場離奇詭異募逞,居然都是意外死亡,警方通過查閱死者的電腦和手機馋评,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門放接,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人留特,你說我怎么就攤上這事纠脾÷耆常” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵苟蹈,是天一觀的道長糊渊。 經常有香客問我,道長慧脱,這世上最難降的妖魔是什么渺绒? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮菱鸥,結果婚禮上宗兼,老公的妹妹穿的比我還像新娘。我一直安慰自己采缚,他們只是感情好针炉,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著扳抽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪殖侵。 梳的紋絲不亂的頭發(fā)上贸呢,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音拢军,去河邊找鬼楞陷。 笑死,一個胖子當著我的面吹牛茉唉,可吹牛的內容都是我干的固蛾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼度陆,長吁一口氣:“原來是場噩夢啊……” “哼艾凯!你這毒婦竟也來了?” 一聲冷哼從身側響起懂傀,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤趾诗,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蹬蚁,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恃泪,經...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年犀斋,在試婚紗的時候發(fā)現(xiàn)自己被綠了贝乎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡叽粹,死狀恐怖览效,靈堂內的尸體忽然破棺而出却舀,到底是詐尸還是另有隱情,我是刑警寧澤朽肥,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布禁筏,位于F島的核電站,受9級特大地震影響衡招,放射性物質發(fā)生泄漏篱昔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一始腾、第九天 我趴在偏房一處隱蔽的房頂上張望州刽。 院中可真熱鬧,春花似錦浪箭、人聲如沸穗椅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽匹表。三九已至,卻和暖如春宣鄙,著一層夾襖步出監(jiān)牢的瞬間袍镀,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工冻晤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留苇羡,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓鼻弧,卻偏偏與公主長得像设江,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子攘轩,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內容