如何注册睡觉事件的Android? [英] How to register to sleep event in Android?
问题描述
我的工作在Android 3.0和我需要知道在我的应用程序时,该设备进入睡眠/关闭屏幕。
I am working on Android 3.0 and I need to know in my application when the device goes on sleep / turn off screen.
我如何可以注册这个意图/事件,因此,我将能够运行在这种情况下一些行动?是否有BroadcastReceiver的,通知该采取任何行动?
How can I register to this intent/event so I will be able to run some actions when this happens? Is there any action in BroadcastReceiver that notifies for this?
推荐答案
此页面有一个教程正是你要找的是什么
This page has a tutorial on exactly what you're looking for.
code从网页复制(为了把这种从一个链接只能回答的东西直接有用的):
Code copied from that page (in order to turn this from a link-only answer to something directly useful):
1)在你的应用程序接收意图创建一个类。例如,下面的接收机是独立的,并设置了一个静态变量在第2部分中使用:
1) Create a class in your application to receive the intent. For example, the following receiver stands alone and sets a static variable to be used in part 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)修改你的活动收到的屏幕开/关事件。您的接收器将在您的广播接收器检查静态变量来知道你刚刚收到的意图的原因:
2) Modify your activity to receive screen on/off events. Your receiver will check the static variable in your broadcast receiver to know the reason for the intent you just received:
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();
}
}
这篇关于如何注册睡觉事件的Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!