java - Android 广播接收器不工作

标签 java android broadcastreceiver

我试图让我的应用程序在屏幕打开时打印一些内容来记录,但它没有按我的预期工作。

这是我的 list 文件中的内容

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


    <receiver android:name="PhoneBroadcastReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.SCREEN_ON"></action>
        </intent-filter>
    </receiver>
</application>

我的接收器看起来像

public class PhoneBroadcastReceiver extends BroadcastReceiver {

public PhoneBroadcastReceiver()
{
}

@Override
public void onReceive(Context _context, Intent _intent) {
    // TODO Auto-generated method stub
    String a = _intent.getAction();


    MessageHandler.log("Received action: " + a); // just a wrapper for printing to a log

}

}

但它不会在日志中打印任何内容。我一直按 Android 电源按钮,屏幕打开/关闭,但我的消息没有出现在日志中。我缺少什么?它看起来与我在网上找到的示例相同。

最佳答案

您无法通过 list 中注册的 BroadcastReceiver 监听 ACTION_SCREEN_ON 广播。您必须从正在运行的组件通过 registerReceiver() 注册它。具有此特征的广播相当少(ACTION_SCREEN_OFFACTION_BATTERY_CHANGED,也许还有 ACTION_USER_PRESENT)。

关于java - Android 广播接收器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698716/

相关文章:

android - 在自定义广播接收器中从推送通知打开时 react native 应用程序崩溃

java - 是否有必要关闭一个 Netty ChunkedInput?

java - 如何将过滤后的流数组输出收集为列表

android - 单击通知未启动由服务创建的我的 PendingIntent

Android NDK 将参数传递给本地方法

android - 从服务发送的广播接收器启动 Activity 时应用程序崩溃

java - 有人可以纠正我理解这段代码的方式,因为输出与我的想法不同吗?

java - 我应该将 boolean 字段设置为易变的吗?

java - 如何在 Android 对话框的 XML 布局文件中指定正确的对话框大小?

java - 在用户选择的时间设置通知