用到的場景很多,自己發揮 ,廢話不多說直接上程式碼:
private classScreenBroadcastReceiverextendsBroadcastReceiver{
privateStringaction= null;
@Override
public voidonReceive(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();
}
}
}
/**
* 開始監聽screen狀態
*
* @paramlistener
*/
public voidbegin(ScreenStateListener listener) {
mScreenStateListener=listener;
registerListener();
getScreenState();
}
/**
* 獲取screen狀態
*/
private voidgetScreenState() {
PowerManagermanager=(PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
if(manager.isScreenOn()) {
if(mScreenStateListener!= null) {
mScreenStateListener.onScreenOn();
}
}else{
if(mScreenStateListener!= null) {
mScreenStateListener.onScreenOff();
}
}
}
/**
* 停止screen狀態監聽
*/
public voidunregisterListener() {
mContext.unregisterReceiver(mScreenReceiver);
}
/**
* 啟動screen狀態廣播接收器
*/
private voidregisterListener() {
IntentFilterfilter= newIntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mContext.registerReceiver(mScreenReceiver,filter);
}
public interfaceScreenStateListener{// 返回給呼叫者螢幕狀態資訊
public voidonScreenOn();
public voidonScreenOff();
public voidonUserPresent();
}
}
複製程式碼
在上面的程式碼中,用到了動態註冊廣播,在需要監聽螢幕狀態的activity中直接呼叫,當不需要監聽的時候,如activity finish的時候,使用unregisterListener解除廣播監聽;
下面是在Activity中呼叫;
ScreenListener screenListener = new ScreenListener(this) ;
screenListener.begin(new ScreenListener.ScreenStateListener() {
@Override
public void onScreenOn() {
Toast.makeText( CounterTActivity.this , "螢幕開啟了" , Toast.LENGTH_SHORT ).show();
}
@Override
public void onScreenOff() {
Toast.makeText( CounterTActivity.this , "螢幕關閉了" , Toast.LENGTH_SHORT ).show();
}
@Override
public void onUserPresent() {
Toast.makeText( CounterTActivity.this , "解鎖了" , Toast.LENGTH_SHORT ).show();
}
});
複製程式碼