Android監聽螢幕解鎖和判斷螢幕狀態

來源:互聯網
上載者:User

Android監聽螢幕解鎖和判斷螢幕狀態

開發後台服務的時候經常需要對螢幕狀態進行判斷,如果是想要監聽螢幕解鎖事件,可以在配置裡面註冊action為 android.intent.action.USER_PRESENT的廣播,則可以監聽解鎖事件。但有時候,在後台執行某個操作時,需要主動判斷螢幕的狀態,比如是否是亮著的,可以使用PowerManager的isScreenOn方法進行判斷,比如螢幕是否開啟了自動旋轉等。

註冊監聽解鎖廣播:

12345 <receiver android:name="com.home.testscreen.MyReceiver"> <intent-filter> <action android:name="android.intent.action.USER_PRESENT" /> intent-filter> receiver>


MyReceiver:

?
12345678910111213141516171819 package com.home.testscreen; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 解鎖 if (intent != null && Intent.ACTION_USER_PRESENT.equals(intent.getAction())) { Toast.makeText(context, "螢幕已解鎖", Toast.LENGTH_SHORT).show(); } } }

主動判斷螢幕是否亮著:

?
1234567 public boolean isScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (pm.isScreenOn()) { return true; } return false; }


判斷是否開啟了重力感應:

?
123456789101112131415161718 /** * 是否開啟了重力感應 * @param context * @return */ public boolean screenIsOpenRotate(Context context) { int gravity = 0; try { gravity = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (gravity == 1) { return true; } return false; }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.