首页 > 解决方案 > 为什么 BroadcastReceiver 不发送 Intent.ACTION_POWER_CONNECTED?

问题描述

我编写了一个应用程序,该应用程序在设备断开/连接到电源时显示祝酒词。我在本教程(第 1 节)中逐步编写了它。

该应用程序什么都不做。我在开头设置了一个断点,onReceive以查看应用程序是否到达那里,并发现onReceive当我断开/连接设备时应用程序没有到达。

应用程序中的问题是什么?

我一点都没变MainActivity

这是我写的课程:

public class CustomReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        String toastMessege = null;
        switch (intentAction) {
            case Intent.ACTION_POWER_CONNECTED:
                toastMessege = "Power connected!";
                break;
            case Intent.ACTION_POWER_DISCONNECTED:
                toastMessege = "Power disconnected!";
                break;
        }
        Toast.makeText(context,toastMessege,Toast.LENGTH_SHORT).show();
    }
}

这是AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.example.powerreceiver">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver
            android:name=".CustomReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
            </intent-filter>
        </receiver>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

标签: androidandroid-intentbroadcastreceiver

解决方案


您需要在运行时注册它们才能正常工作


推荐阅读