我正在使用Android 3.0,我需要在我的应用程序中知道设备何时进入睡眠状态/关闭屏幕.
如何注册此意图/事件,以便在发生这种情况时能够执行某些操作?BroadcastReceiver中有任何动作可以通知吗?
mah*_*mah 13
这个页面有一个关于你正在寻找什么的教程.
从该页面复制的代码(为了将其从仅链接答案转换为直接有用的答案):
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
2)修改您的活动以接收屏幕开/关事件.您的接收器将检查广播接收器中的静态变量,以了解您刚收到的意图的原因:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8882 次 |
| 最近记录: |