<application>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"></action>
</intent-filter>
</receiver>
...
</application>
设置MyBroadcastReceiver
只是为了将foo输出到日志。什么也不做。有什么建议吗?是否需要分配任何权限才能捕获意图?
发布于 2009-10-19 11:55:10
我认为,这些操作只能由在Java代码中注册的接收者(通过registerReceiver()
)接收,而不能通过清单中注册的接收者接收。
发布于 2011-09-07 17:55:23
或者,您可以使用电源管理器来检测屏幕锁定。
@Override
protected void onPause()
{
super.onPause();
// If the screen is off then the device has been locked
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
isScreenOn = powerManager.isInteractive();
} else {
isScreenOn = powerManager.isScreenOn();
}
if (!isScreenOn) {
// The screen has been locked
// do stuff...
}
}
发布于 2013-04-22 15:34:10
"android.intent.action.HEADSET_PLUG"
"android.intent.action.ACTION_SCREEN_ON"
"android.intent.action.ACTION_SCREEN_OFF"
上面的三个,他们不能使用Manifest注册。Android core向它们添加了"Intent.FLAG_RECEIVER_REGISTERED_ONLY“(也许..我只在"HEADSET_PLUG“的情况下检查了代码。
因此,我们应该使用“动态寄存器”。就像下面..。
private BroadcastReceiver mPowerKeyReceiver = null;
private void registBroadcastReceiver() {
final IntentFilter theFilter = new IntentFilter();
/** System Defined Broadcast */
theFilter.addAction(Intent.ACTION_SCREEN_ON);
theFilter.addAction(Intent.ACTION_SCREEN_OFF);
mPowerKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String strAction = intent.getAction();
if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) {
// > Your playground~!
}
}
};
getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}
private void unregisterReceiver() {
int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 7) {
try {
getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
}
catch (IllegalArgumentException e) {
mPowerKeyReceiver = null;
}
}
else {
getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
mPowerKeyReceiver = null;
}
}
https://stackoverflow.com/questions/1588061
复制相似问题