广播接收器不工作(如果检测到无线连接) [英] BroadcastReceiver is not working (detect if wifi is connected)
问题描述
我试图用一个BroadcastReceiver来检测,如果无线网络连接,并只显示敬酒时的状态变化(WIFI disonnect /重新连接/关闭),但它似乎并不奏效。任何想法?
I'm trying to use a BroadcastReceiver to detect if wifi is connected and simply display a toast when the status changes (wifi disonnect/reconnect/turn off) but it doesn't seem to be working. Any ideas?
ConnectionChangeReceiver类:
ConnectionChangeReceiver class:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final boolean isWifiConn = networkInfo.isConnected();
Log.d("debug", "Wifi connected: " + isWifiConn);
Toast toast = Toast.makeText(context, "Wifi connected: " + isWifiConn, Toast.LENGTH_LONG);
toast.show();
}
}
清单:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<receiver android:name="ConnectionChangeReceiver" android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
我走在应用程序,并断开无线网络连接,重新连接,没有面包。我禁用无线网络,没有面包。重新启用它,没有面包。我怀疑,有一些错误的广播接收机。
I go in the app, and disconnect wifi, reconnect, no toast. I disable wifi, no toast. re-enable it, no toast. I suspect that there's something wrong with the broadcast receiver.
先谢谢了。
推荐答案
我得到了它的工作。
我的问题是在清单中。我把我的接收器模块应用程序标记之外。有一次,我内移动它,它完美地工作。
My problem was in the Manifest. I was putting my receiver block outside the application tag. Once I moved it inside, it worked perfectly.
这篇关于广播接收器不工作(如果检测到无线连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!