gpt4 book ai didi

android - onReceive 从未调用过

转载 作者:行者123 更新时间:2023-11-29 02:16:08 28 4
gpt4 key购买 nike

我有以下代码我想检测手机屏幕但是永远不会调用函数 onReceive谁能给我一个解决方案。请帮忙。如果有人有任何其他工作代码,请提供帮助。谢谢

package com.pack;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class Screen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
Context con = this;
this.registerReceiver(new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Screen off...................");
}
}, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}

}

最佳答案

您的代码对我有用。我修改了代码,使其更易于阅读并添加了一些系统输出,但它的工作方式与您编写的方式相同:

public class Test extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Screen off...................");
}

}, filter);
}

@Override
protected void onResume() {
super.onResume();
System.out.println("onResume()");
}

@Override
protected void onDestroy() {
super.onDestroy();
System.out.println("onDestroy()");
}

@Override
protected void onPause() {
super.onPause();
System.out.println("onPause()");
}

如果我这样做(启动 Activity 、关闭屏幕、打开屏幕、按返回按钮),它会打印以下内容:

onResume()
onPause()
Screen off...................
onResume()
onPause()
onDestroy()

在此之后, Activity 被销毁,因此不会显示任何事件。也许您想改为在 AndroidManifest 中注册 BroadcastReceiver。

关于android - onReceive 从未调用过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3753019/

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