android - 为什么 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>
解决方案
您需要在运行时注册它们才能正常工作
推荐阅读
- javascript - 按类样式化反应渲染的 HTML
- python - discord.py bot ClientConnectorCertificateError 运行时
- paypal - 用于市场和平台的贝宝 | 订阅平台费可用吗?
- cookies - 如何管理 Cookies are required 错误页面?
- docker - 无法连接到 minikube 外部服务或入口
- node.js - 待办事项列表 NodeJs -CSS 文件未链接
- single-sign-on - Keycloak SSO 会话最大值 = 0?
- java - Hibernate 验证器不工作并且 BindingResult.hasErrors 在春季启动时总是返回 false
- php - Woocommerce 批量定价尝试访问 bool 类型值的数组偏移量
- c++ - 使用 P-RNG 时需要缩小转换范围