我正在开发 Android 3.0,我需要在我的应用程序中知道设备何时进入睡眠/关闭屏幕。
我如何注册此意图/事件,以便在发生这种情况时我能够运行一些操作? BroadcastReceiver 中是否有任何通知此操作的操作?
This http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/页面上有一个关于您正在寻找的内容的教程。
从该页面复制的代码(为了将其从仅链接的答案转变为直接有用的答案):
1) 在您的应用程序中创建一个类来接收意图。例如,以下接收器独立并设置要在第 2 部分中使用的静态变量:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
}
2) 修改您的 Activity 以接收屏幕开/关事件。您的接收器将检查广播接收器中的静态变量,以了解您刚刚收到的意图的原因:
public class ExampleActivity extends Activity {
@Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// your code
}
@Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}
@Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)