0

我在我的主活动中设置了一个动态广播接收器,当我的网络状态发生变化时,它应该显示一条 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();
        }
    }
}}
4

2 回答 2

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)
    );
于 2017-02-19T12:08:53.520 回答
0

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

于 2017-02-19T11:56:56.330 回答