gpt4 book ai didi

android - 监听 ACTION_SCREEN_OFF

转载 作者:IT王子 更新时间:2023-10-28 23:35:14 30 4
gpt4 key购买 nike

我正在尝试启动一个在后台运行的服务,该服务正在监听 ACTION_SCREEN_OFF,当它找到 ACTION_SCREEN_OFF 时,启动我的 Activity 。

我在某处读到您需要创建一个BroadcastReceiver,因为将它放在 list XML 中是行不通的。但是,经过大量搜索,我不知道从哪里开始。

最佳答案

您不能在 AndroidManifest.xml 中声明 ACTION_SCREEN_ONACTION_SCREEN_OFF。您只能在 Activity 运行时捕捉它们。

这是一个例子。

广播接收器:

public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

@Override
public void onReceive(final Context context, final 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;
}
}

}

Activity :

public class ExampleActivity extends Activity {

private BroadcastReceiver mReceiver = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize receiver
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
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
Log.e("MYAPP", "SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}

@Override
protected void onResume() {
super.onResume();
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
Log.e("MYAPP", "SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
}

@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
super.onDestroy();
}

}

您可能可以通过从 Service 监听这些事件来解决您的问题。

关于android - 监听 ACTION_SCREEN_OFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346958/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com