我正在尝试使用广播接收器类获取WiFi连接更改事件。我已经在三星S7 edge和HTC 626Q上进行了测试,效果很好(即使应用程序关闭),但如果应用程序关闭,这在华为GR5 2017上不起作用。只有当应用程序在屏幕上运行时,它才起作用。S7和GR5设备都有Android 7(牛轧糖)操作系统。
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getAction(),Toast.LENGTH_SHORT).show();
}
}
AndroidManifest文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="chanakamadurangakarunarathne.testbroadcastevents">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".NetworkChangeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.nsd.STATE_CHANGED" />
<action android:name="android.net.wifi.NETWORK_IDS_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.p2p.CONNECTION_STATE_CHANGE" />
<action android:name="android.net.wifi.p2p.DISCOVERY_STATE_CHANGE" />
<action android:name="android.net.wifi.p2p.PEERS_CHANGED" />
<action android:name="android.net.wifi.p2p.STATE_CHANGED" />
<action android:name="android.net.wifi.p2p.THIS_DEVICE_CHANGED" />
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.supplicant.STATE_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
我知道我可以使用服务,但如果我可以在所有设备上使用广播接收器就好了。
我发现了很多关于“广播接收器不工作背景”的问题,但我找不到答案。