我正在为我的应用添加一个wifi检查,阻止用户在没有有效连接的情况下做任何事情。
在研究了一些stackoverflow问题后,我将其添加到我的主要活动中:
public AppWifiManager appWifiManager;
this.appWifiManager = new AppWifiManager();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(this.appWifiManager, intentFilter);
if(this.appWifiManager.connected){
System.out.println("Connected to wifi!");
}
else{
System.out.println("Not connected to wifi!");
}
接下来,appWifiManager是一个扩展BroadcastReceiver的类:
package flarehubpe.xflare.flarehub;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
public class AppWifiManager extends BroadcastReceiver{
public boolean connected = false;
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
System.out.println("CALLED");
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
this.connected = info.isConnected();
}
}
}
最后,在我的Android清单中我注册了:
<receiver android:name="flarehubpe.xflare.flarehub.AppWifiManager">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE"/>
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.NETWORK_STATE_CHANGED_ACTION"/>
<uses-permission android:name="android.permission.EXTRA_NETWORK_INFO"/>
我添加了一些简单的调试脚本,代码无效。我的覆盖onReceive方法永远不会被调用。为什么android没有调用我的方法?因此,我无法获得应用程序的真正连接状态。