要在Android應用中構建關閉離線模式,可以按照以下步驟進行:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<TextView
android:id="@+id/networkStatusTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Network Status" />
public class MainActivity extends AppCompatActivity {
private TextView networkStatusTextView;
private BroadcastReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkStatusTextView = findViewById(R.id.networkStatusTextView);
networkChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
networkStatusTextView.setText("Online");
} else {
networkStatusTextView.setText("Offline");
}
}
};
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
這樣,當應用運行時,它將監測網絡連接狀態的改變,并將其顯示在TextView中。如果網絡連接斷開,TextView將顯示"Offline";如果網絡連接恢復,TextView將顯示"Online"。