我实现了这是在我的onCreate()主要活动注册接收器的方式,只要定义接收器事先地方:
lockScreenReceiver = new LockScreenReceiver();
IntentFilter lockFilter = new IntentFilter();
lockFilter.addAction(Intent.ACTION_SCREEN_ON);
lockFilter.addAction(Intent.ACTION_SCREEN_OFF);
lockFilter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(lockScreenReceiver, lockFilter);
然后的onDestroy():
unregisterReceiver(lockScreenReceiver);
在接收器必须抓住以下情况:
public class LockScreenReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if (intent != null && intent.getAction() != null)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
// Screen is on but not unlocked (if any locking mechanism present)
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
// Screen is locked
}
else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
// Screen is unlocked
}
}
}
}
来源
2016-07-13 08:25:53
box
OK,我只是想通。这背后的理由是什么? – ohnoes 2009-10-19 12:06:06
对于那些他们真的不想启动一个新流程的情况,Android似乎不支持清单注册的接收器。例如,您将看到与电池信息操作(例如,BATTERY_LOW)相同的效果。但是,除此之外,我没有太多理由 - 我没有写出来。 :-) – CommonsWare 2009-10-19 12:50:33
@CommonsWare那么我怎样才能registerReceiver()当按下电源按钮? – Venky 2012-06-21 06:16:53