2017年5月10日 星期三

防止手機進入待命狀態(2017新更新) - Android 新手學習筆記

以前有寫過一篇同標題的文章「防止手機進入待命狀態」,但也不知是之前沒用正確,還是目前已不合時宜了,總之這篇是最新的用法

在官方文件中有一篇「Keeping the Device Awake」的文章,以下是大致的內容

要保持設備"醒著",有分兩種狀況:

  • 保持螢幕常亮(Keep the Screen On)
  • 保持CPU運作(Keep the CPU On)

以下分別說明


保持螢幕常亮(Keep the Screen On)


大部份的需求大概是這種,例如用於遊戲,或播放影片等,這種需求不需要加入額外的權限,實際做法有兩種:

  • 如果是某個畫面固定要保持螢幕常亮,則直接在 layout xml 中加入 android:keepScreenOn="true" 屬性即可,例如
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true">
        ...
    </RelativeLayout>
  • 如果需要動態開關,則程式語法如下:
    //開的語法
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
    //關的語法
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    


保持CPU運作(Keep the CPU On)


使用時機:需要在背景完成一些事,此時 CPU 雖是 On,但 Screen 是 Off 的

原則:

  • 保持 CPU On 的時間應該盡可能的短
  • 應該用於背景服務,不要在 Activity 中使用 CPU On (Activity 應該要用 Screen On)


實際做法如下:
  1. 在 AndroidManifest.xml 加入
    <uses-permission android:name="android.permission.WAKE_LOCK" />
  2. 程式語法:
    //開的語法
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "MyWakelockTag");
    wakeLock.acquire();
    
    //關的語法
    wakelock.release();
    

但如果 App 有 broadcast receiver,則做法不同,這裡先不談,請參考原文說明

沒有留言:

張貼留言

廣告訊息會被我刪除

Related Posts with Thumbnails