Android 监听锁屏、解锁、开屏 功能代码
1、首先定义ScreenListener
packagecom.app.lib; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.content.IntentFilter; importandroid.os.PowerManager; /** *Createdby${zyj}on2016/6/21. */ publicclassScreenListener{ privateContextmContext; privateScreenBroadcastReceivermScreenReceiver; privateScreenStateListenermScreenStateListener; publicScreenListener(Contextcontext){ mContext=context; mScreenReceiver=newScreenBroadcastReceiver(); } /** *screen状态广播接收者 */ privateclassScreenBroadcastReceiverextendsBroadcastReceiver{ privateStringaction=null; @Override publicvoidonReceive(Contextcontext,Intentintent){ action=intent.getAction(); if(Intent.ACTION_SCREEN_ON.equals(action)){//开屏 mScreenStateListener.onScreenOn(); }elseif(Intent.ACTION_SCREEN_OFF.equals(action)){//锁屏 mScreenStateListener.onScreenOff(); }elseif(Intent.ACTION_USER_PRESENT.equals(action)){//解锁 mScreenStateListener.onUserPresent(); } } } /** *开始监听screen状态 * *@paramlistener */ publicvoidbegin(ScreenStateListenerlistener){ mScreenStateListener=listener; registerListener(); getScreenState(); } /** *获取screen状态 */ privatevoidgetScreenState(){ PowerManagermanager=(PowerManager)mContext .getSystemService(Context.POWER_SERVICE); if(manager.isScreenOn()){ if(mScreenStateListener!=null){ mScreenStateListener.onScreenOn(); } }else{ if(mScreenStateListener!=null){ mScreenStateListener.onScreenOff(); } } } /** *停止screen状态监听 */ publicvoidunregisterListener(){ mContext.unregisterReceiver(mScreenReceiver); } /** *启动screen状态广播接收器 */ privatevoidregisterListener(){ IntentFilterfilter=newIntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); mContext.registerReceiver(mScreenReceiver,filter); } publicinterfaceScreenStateListener{//返回给调用者屏幕状态信息 publicvoidonScreenOn(); publicvoidonScreenOff(); publicvoidonUserPresent(); } }
2、使用
packagecom.app.lib; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.widget.Toast; publicclassMainActivityextendsAppCompatActivity{ privateScreenListenerscreenListener; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); screenListener=newScreenListener(MainActivity.this); screenListener.begin(newScreenListener.ScreenStateListener(){ @Override publicvoidonScreenOn(){ Toast.makeText(MainActivity.this,"屏幕打开了",Toast.LENGTH_SHORT).show(); } @Override publicvoidonScreenOff(){ Toast.makeText(MainActivity.this,"屏幕关闭了",Toast.LENGTH_SHORT).show(); } @Override publicvoidonUserPresent(){ Toast.makeText(MainActivity.this,"解锁了",Toast.LENGTH_SHORT).show(); } }); } }
以上所述是小编给大家介绍的Android监听锁屏、解锁、开屏功能代码的相关知识,希望对大家有所帮助!