要在Android應(yīng)用中構(gòu)建關(guān)閉離線模式,可以按照以下步驟進(jìn)行:
<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" />
這樣,當(dāng)應(yīng)用運(yùn)行時(shí),它將監(jiān)測(cè)網(wǎng)絡(luò)連接狀態(tài)的改變,并將其顯示在TextView中。如果網(wǎng)絡(luò)連接斷開,TextView將顯示"Offline";如果網(wǎng)絡(luò)連接恢復(fù),TextView將顯示"Online"。