我有一个清单注册的BroadcastReceiver,用于监控WiFi断开连接。每次设备扫描WiFi时,我都会收到断开广播。我需要一些方法来确定广播是否是扫描WiFi或实际与网络断开的设备的结果。
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
if(!intent.getAction().equals("android.net.wifi.STATE_CHANGE"))
return;
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if(networkInfo.getDetailedState() == CONNECTED || networkInfo.getDetailedState() == DISCONNECTED)
PresenceData.loadData(context);
if(networkInfo.getDetailedState() == CONNECTED) {
System.out.println("Wifi connected");
PresenceData.sendNotification("Wifi Connected", "You are now connected to " + PresenceData.getCurrentWifiSSID(context), context);
PresenceData.submitChanges(context);
} else if(networkInfo.getDetailedState() == DISCONNECTED) {
System.out.println("Wifi Disconnected");
PresenceData.sendNotification("Wifi Disconnected", "Your wifi has disconnected", context);
UpdaterService.scheduleUpdate(context);
}
}
}
}
}
答案 0 :(得分:0)
您可以尝试使用NetworkInfo.State来获取网络的当前状态。有各种可能状态的枚举,例如失败,成功,扫描等。下面是如何检索信息的示例:
public class MainActivity extends AppCompatActivity {
private ConnectivityManager connectivityManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.connectivityManager = (ConnectivityManager)
this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
System.out.println("Network Status " + info.getDetailedState().name());
}
}