如何在 Android 上检查网络连接可用性?
此示例演示了如何在 Android 中检查网络连接的可用性。
步骤 1 − 在 Android Studio 中新建一个项目,转到文件 ⇒ 新建项目并填写所有必需的详细信息以创建新项目
步骤 2 − 添加以下代码到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Connection Status: " android:textSize="20sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
步骤 3 − 添加以下代码到 src/MainActivity.java
import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (haveNetwork()){ Toast.makeText(MainActivity.this, "Network connection is available", Toast.LENGTH_SHORT).show(); } else if (!haveNetwork()) { Toast.makeText(MainActivity.this, "Network connection is not available", Toast.LENGTH_SHORT).show(); } } private boolean haveNetwork(){ boolean have_WIFI= false; boolean have_MobileData = false; ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo(); for(NetworkInfo info:networkInfos){ if (info.getTypeName().equalsIgnoreCase("WIFI"))if (info.isConnected())have_WIFI=true; if (info.getTypeName().equalsIgnoreCase("MOBILE DATA"))if (info.isConnected())have_MobileData=true; } return have_WIFI||have_MobileData; } }
步骤 4 − 添加以下代码到 androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
让我们尝试运行你的应用程序。我假设你已将真正的 Android 移动设备连接到计算机。要从 Android Studio 运行应用程序,请打开一个项目的活动文件并点击工具栏中的“运行 ”图标。选择你的移动设备作为选项,然后查看将显示默认界面的移动设备 −
点击 此处 下载项目代码。
广告