Android:監控網路連線變化
為了監控網路連線變化,Android 提供了 ConnectivityManager.NetworkCallback 類別。與傳統的 BroadcastReceiver 相比,這允許更精細的監聽。實作方法如下:
<code class="java">public class ConnectivityMonitor extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { // Internet connectivity is available Log.d("Connectivity", "Internet connected"); } @Override public void onLost(Network network) { // Internet connectivity is lost Log.d("Connectivity", "Internet disconnected"); } }</code>
要註冊此回調,您需要建立一個ConnectivityManager 實例並呼叫registerNetworkCallback 方法:
<code class="java">ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); connectivityManager.registerNetworkCallback(new NetworkRequest.Builder().build(), new ConnectivityMonitor());</code>
您也可以使用預先定義的連線狀態:ConnectivityManager 的狀態:
<code class="java">if (connectivityManager.getActiveNetworkInfo() != null) { // Connected to a network if (connectivityManager.getActiveNetworkInfo().isConnectedToWifi()) { // Connected via WiFi } else { // Connected via mobile data } } else { // Not connected to a network }</code>
完成後請記得取消註冊回呼:
<code class="java">connectivityManager.unregisterNetworkCallback(new ConnectivityMonitor());</code>
以上是如何監控 Android 應用程式中的網路連線變化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!