Android监听按键锁屏广播
Posted zhangjin1120
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android监听按键锁屏广播相关的知识,希望对你有一定的参考价值。
目录
java版
不需要xml代码,直接java代码注册就好。
public class MainActivity extends AppCompatActivity
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final IntentFilter filter = new IntentFilter();
// 屏幕灭屏广播
filter.addAction(Intent.ACTION_SCREEN_OFF);
// 屏幕亮屏广播
filter.addAction(Intent.ACTION_SCREEN_ON);
BroadcastReceiver mScreenInfoReceiver = new BroadcastReceiver()
@Override
public void onReceive(final Context context, final Intent intent)
Log.d(TAG, "onReceive");
String action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action))
Log.d(TAG, "screen on");
else if (Intent.ACTION_SCREEN_OFF.equals(action))
Log.d(TAG, "screen off");
;
registerReceiver(mScreenInfoReceiver, filter);
按锁屏键,测试效果:
kotlin版本
class MainActivity : AppCompatActivity()
companion object
private const val TAG = "MainActivity"
class ScreenReceiver : BroadcastReceiver()
override fun onReceive(context: Context, intent: Intent)
Log.d(TAG, "onReceive: ")
var action = intent.getAction()
if (Intent.ACTION_SCREEN_ON.equals(action))
Log.d(TAG, "screen on")
else if (Intent.ACTION_SCREEN_OFF.equals(action))
Log.d(TAG, "screen off")
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val filter = IntentFilter()
filter.addAction(Intent.ACTION_SCREEN_OFF)
filter.addAction(Intent.ACTION_SCREEN_ON)
var receiver = ScreenReceiver()
registerReceiver(receiver, filter)
按锁屏键,测试效果:
以上是关于Android监听按键锁屏广播的主要内容,如果未能解决你的问题,请参考以下文章