2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
系統(tǒng)會(huì)發(fā)送廣播
Intent.ACTION_SCREEN_OFF
Intent.ACTION_SCREEN_ON
Intent.ACTION_USER_PRESENT

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
捕捉自動(dòng)休眠灰屏的事件,可以通過監(jiān)聽系統(tǒng)的廣播獲得當(dāng)前手機(jī)屏幕的狀態(tài),廣播需要在注冊(cè)文件中注冊(cè),具體的實(shí)現(xiàn)代碼如下:
public class ScreenListener {
private Context mContext;
private ScreenBroadcastReceiver mScreenReceiver;
private ScreenStateListener mScreenStateListener;
public ScreenListener(Context context) {
mContext = context;
mScreenReceiver = new ScreenBroadcastReceiver();
}
/**
* screen狀態(tài)廣播接收者
*/
private class ScreenBroadcastReceiver extends BroadcastReceiver {
private String action = null;
@Override
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) { // 開屏
mScreenStateListener.onScreenOn();
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 鎖屏
mScreenStateListener.onScreenOff();
} else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解鎖
mScreenStateListener.onUserPresent();
}
}
}
/**
* 開始監(jiān)聽screen狀態(tài)
*
* @param listener
*/
public void begin(ScreenStateListener listener) {
mScreenStateListener = listener;
registerListener();
getScreenState();
}
/**
* 獲取screen狀態(tài)
*/
private void getScreenState() {
PowerManager manager = (PowerManager) mContext
.getSystemService(Context.POWER_SERVICE);
if (manager.isScreenOn()) {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOn();
}
} else {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOff();
}
}
}
/**
* 停止screen狀態(tài)監(jiān)聽
*/
public void unregisterListener() {
mContext.unregisterReceiver(mScreenReceiver);
}
/**
* 啟動(dòng)screen狀態(tài)廣播接收器
*/
private void registerListener() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mContext.registerReceiver(mScreenReceiver, filter);
}
public interface ScreenStateListener {// 返回給調(diào)用者屏幕狀態(tài)信息
public void onScreenOn();
public void onScreenOff();
public void onUserPresent();
}
}
在上面的代碼中,用到了動(dòng)態(tài)注冊(cè)廣播,在需要監(jiān)聽屏幕狀態(tài)的activity中,當(dāng)不需要監(jiān)聽的時(shí)候,如activity finish的時(shí)候,使用unregisterListener解除廣播監(jiān)聽;
下面是在Activity中調(diào)用;
ScreenListener l = new ScreenListener(this);
l.begin(new ScreenStateListener() {
@Override
public void onUserPresent() {
Log.e("onUserPresent", "onUserPresent");
}
@Override
public void onScreenOn() {
Log.e("onScreenOn", "onScreenOn");
}
@Override
public void onScreenOff() {
Log.e("onScreenOff", "onScreenOff");
}
});
通過以上步驟即實(shí)現(xiàn)了對(duì)屏幕狀態(tài)的監(jiān)聽.
- 2 回答
- 0 關(guān)注
- 264 瀏覽
添加回答
舉報(bào)