【发布时间】:2019-10-23 13:17:53
【问题描述】:
我编写了一个应用程序,该应用程序在设备断开/连接到电源时显示祝酒词。我用this教程(第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>
【问题讨论】:
-
您链接的课程已弃用。自 android Oreo 以来,清单中声明的隐式广播接收器将不再工作,除非它们在 exceptions 列表中。
-
在较新的版本中有这些意图的替代品吗?
标签: android android-intent broadcastreceiver