据我所知,如果我想在每次网络状态更改时检查我的互联网连接,我必须创建一个BroadcastReceiver。
我已将权限添加到我的清单中,并创建了以下类:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
Log.d("Netowk Available ", "Flag No 1");
}
else
{
Log.d("Network not Available","Network is not available");
}
}
}
我不明白的唯一想法是如何让听众看到变化。我在我的活动中覆盖了onResume和onPause,但没有任何反应:
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
registerReceiver(myBroadcast, new IntentFilter());
}
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
unregisterReceiver(myBroadcast);
}
答案 0 :(得分:2)
你必须将BroadcastReceiver放入你的Activity中,就像这个答案所指出的那样:https://stackoverflow.com/a/4011057/1758048
问候。