我想知道是否有可能在应用程序清单中注册广播接收器以检测屏幕的开启/关闭。
我不喜欢编程方式的原因是它需要应用程序在运行时才能检测到这样的事情,而“在清单中注册广播接收器的应用程序在广播接收器执行时无需运行”(出处:《Professional Android 2 Application Development》书籍)。
我的应用程序实际上是一个锁屏应用程序,如果使用可编程方法,则需要一直运行:S
有没有解决的办法?
我在清单中尝试以下内容:
<receiver android:name=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
还有一个简单的MyBroadCastReciever类:
public class MyBroadCastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("Check","Screen went OFF");
Toast.makeText(context, "screen OFF",Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("Check","Screen went ON");
Toast.makeText(context, "screen ON",Toast.LENGTH_LONG).show();
}
}
}