任务是检查手机是否已连接到互联网。我有问题。 即使关闭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:是否有任何Connection监听器,以及如何检查Internet信号强度(3G,4G,WiFi)?
答案 0 :(得分: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);
}
}
}