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