1

任务是检查手机是否连接到互联网。我有问题。即使wifi关闭,它也会显示“已连接”。这是我的课。

public class InterneProvjera {
    Context context;
    @SuppressLint("MissingPermission")
    public InterneProvjera(Context context){
        this.context = context;
    }

    public boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (NetworkInfo i: info) {
                    if (i.getState() == NetworkInfo.State.CONNECTED)
                        return true;
                }
            }
        }
        return false;
    }
}

这是主要活动:

InterneProvjera interneProvjera = new InterneProvjera(this);
        String tKonekcija = (interneProvjera.isNetworkAvailable()) ?  "Connected" : "No connection";
        txtIspis.setText(tKonekcija);

抱歉,如果它在 android 编程中是新的,那么它的微不足道的问题。Ps:是否有任何连接监听器以及如何检查互联网信号强度(3G、4G、wifi)?

4

1 回答 1

2

您应该使用BroadcastReceiver来检查网络状态ConnectivityManager

以下是检查网络是否连接的代码。如果已连接,它将在以下位置显示网络名称Toast

ConnectivityStatusReceiver.java

public class ConnectivityStatusReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

    if (activeNetworkInfo != null) {
      Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
    }
  }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {
  ConnectivityStatusReceiver connectivityStatusReceiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    connectivityStatusReceiver = new ConnectivityStatusReceiver();
  }

  @Override
  protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityStatusReceiver, intentFilter);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (connectivityStatusReceiver != null) {
      // unregister receiver
      unregisterReceiver(connectivityStatusReceiver);
    }
  }
}
于 2018-07-19T00:39:30.900 回答