我正在使用 BroadcastReciever 来检查互联网连接,但它会在活动开始时调用。这是我的 BroadcastReceiver
public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileNwConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
try {
if (isWifiConnected || isMobileNwConnected) {
Snackbar.make(cordinatorlayout, "Connection established", Snackbar.LENGTH_INDEFINITE)
.setAction("GO ONLINE", new View.OnClickListener() {
@Override
public void onClick(View view) {
//Toast.makeText(context, "clicked", Toast.LENGTH_SHORT).show();
finish();
startActivity(getIntent());
}
}).show();
}else {
Snackbar.make(cordinatorlayout, "You are Offline", Snackbar.LENGTH_INDEFINITE).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
};
` and I have registered BroadcastReceiver inside oncreate() of MainActivity. My BroadcastReceiver is getting called but it is getting called at the start of activity.
答案 0 :(得分:0)
当您设置BroadcastReceiver
时,它最初会被调用一次。之后,它开始侦听Internet连接状态的变化,并在每次状态更改时调用。
如果您希望仅在Internet连接从DISCONNECTED
更改为CONNECTED
时才调用它,请创建一个保存当前状态的变量。当您在接收器中收到CONNECTED
时,请检查变量是否为DISCONNECTED
。如果是这样,做你想做的事;否则,什么都不做。