我试图从CONNECTIVITY_ACTION接收BroadcastMessages:
// register BroadcastReceiver on network state changes
final IntentFilter mIFNetwork = new IntentFilter();
mIFNetwork.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
registerReceiver(mIRNetwork, mIFNetwork);
和接收者是:
private BroadcastReceiver mIRNetwork = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
android.util.Log.i(TAG,"mIRNetwork: Network State Received: "+intent.getAction());
Bundle extras = intent.getExtras();
if (extras!=null){
android.util.Log.i(TAG,"mIRNetwork: ACTION_BACKGROUND_DATA_SETTING_CHANGED: "+extras.getString(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
android.util.Log.i(TAG,"mIRNetwork: CONNECTIVITY_ACTION: "+extras.getString(ConnectivityManager.CONNECTIVITY_ACTION));
android.util.Log.i(TAG,"mIRNetwork: EXTRA_EXTRA_INFO: "+extras.getString(ConnectivityManager.EXTRA_EXTRA_INFO));
android.util.Log.i(TAG,"mIRNetwork: EXTRA_NO_CONNECTIVITY: "+extras.getString(ConnectivityManager.EXTRA_NO_CONNECTIVITY));
android.util.Log.i(TAG,"mIRNetwork: EXTRA_REASON: "+extras.getString(ConnectivityManager.EXTRA_REASON));
}
}
简而言之,总是空的。我认为,如果我松散WiFi连接,我应该得到EXTRA_NO_CONNECTIVITY(因为它是互联网的唯一途径)或至少从列表中的东西。但没有运气。如果我断开我的WiFi AP接收器获取他的消息,但有额外的空。当我再次打开我的WiFi接收器发射但没有额外的时候......为什么会这样?如何知道该应用程序丢失了任何网络连接?我想是这样的。
答案 0 :(得分:16)
你不能得到额外的但你可以通过这种方式获得数据
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager
.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo info1 = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
.EXTRA_NETWORK_INFO);
NetworkInfo info2 = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager
.EXTRA_OTHER_NETWORK_INFO);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean failOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.d("MY_TAG", "onReceive(): mNetworkInfo=" + info1 + " mOtherNetworkInfo = " +
(info2 == null ? "[none]" : info2 + " noConn=" + noConnectivity));
}
}
有关详细信息,请参阅此
答案 1 :(得分:4)
Dharmendras answer很好。但请注意,EXTRA_NETWORK_INFO
现已弃用(自Api等级14以来),Android文档会说明以下内容:
由于NetworkInfo可能因UID而异,因此应用程序应始终通过
getActiveNetworkInfo()
获取网络信息。
这实际上让我们很容易。您可以重复使用之前可能执行的连接检查,并执行以下操作:
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this)
checkConnection();
}
}
private void checkConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo()
.isConnectedOrConnecting()) {
// do something
}
}
假设您在注册广播的活动中。
这还有一个额外的好处,即尽可能短暂地监听连接广播的最佳实践,outlined here:)