我正在尝试启动在后台运行的服务,该服务正在侦听ACTION_SCREEN_OFF
,当它找到ACTION_SCREEN_OFF
时,会启动我的活动。
我在某处读到了创建 BroadcastReceiver 所需的内容,因为将它放在清单XML中是行不通的。但是我不知道经过多次搜索后从哪里开始。
答案 0 :(得分:38)
您无法在 AndroidManifest.xml 中声明ACTION_SCREEN_ON
和ACTION_SCREEN_OFF
。
您只能在活动开始时捕获它们。
这是一个例子。
BroadcastReceiver :
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;
}
}
}
活动:
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
收听这些事件来解决您的问题。
答案 1 :(得分:0)
我正在使用来自async categorySearch() {
this.searchFlag = true;
console.log(this.newSearch)
console.log(this.tagLocation)
let a =await bigQueryApi.querygo()
console.log(a)
}
的回调来解决问题ScreenReceiver
和onResume()
。这些在onPause()
之前被调用。