检查在线连接始终返回True

时间:2017-02-19 11:48:33

标签: android broadcastreceiver android-connectivitymanager

我的主要活动中设置了动态广播接收器,每当我的网络状态发生变化时,都会显示Toast消息。我在线连接,运行应用程序,"你在线!" Toast消息显示,然后我在我的笔记本电脑上关闭了互联网,导航回我的主要活动并且我一直保持相同的状态"你在线!"吐司。我正在检查我的日志语句和我的NetworkInfo对象保持返回,我确实在线,当我显然没有。我在我的模拟器和手机上试过这个。有谁知道为什么?

这是我的主要活动,其中包含我的嵌套广播接收器类,意图过滤器和执行Toast的方法:

public class MainActivity extends AppCompatActivity {
private IntentFilter onlineIntentFilter;
private CheckOnlineReceiver checkOnlineReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    onlineIntentFilter = new IntentFilter();
    checkOnlineReceiver = new CheckOnlineReceiver();
    onlineIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    }


@Override
protected void onResume() {
    super.onResume();
    registerReceiver(checkOnlineReceiver, onlineIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(checkOnlineReceiver);
}


public void isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    Log.v("TAG", "NETWORK INFO =========== " + networkInfo);
    if (networkInfo != null && networkInfo.isConnected()) {
        Toast.makeText(this,"You Are Online!",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this,"You Are Not Online!",Toast.LENGTH_LONG).show();
    }
}
private class CheckOnlineReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        boolean stateChanged = (action.equals(ConnectivityManager.CONNECTIVITY_ACTION));
        if (stateChanged){
            isNetworkAvailable();
        }
    }
}}

2 个答案:

答案 0 :(得分:1)

我将这样做:

private class CheckOnlineReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive action: " + intent.getAction());
        Log.d(TAG, "onReceive component: " + intent.getComponent());
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        stateChanged = networkInfo != null && networkInfo.isConnectedOrConnecting();

    if (stateChanged) {
        Toast.makeText(this,"You Are Online!",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this,"You Are Not Online!",Toast.LENGTH_LONG).show();
       }
    }
}

使用以下内容替换您的接收器代码:

registerReceiver(
            checkOnlineReceiver,
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
    );

答案 1 :(得分:0)

您是否尝试在模拟器上关闭WiFi,看看会发生什么? networkInfo.isConnected()不检查互联网。它只是意味着有一个活跃的连接。