จัดการการใช้งานเครือข่าย

บทเรียนนี้จะอธิบายวิธีเขียนแอปพลิเคชันที่มีการควบคุมแบบละเอียด เกี่ยวกับการใช้ทรัพยากรเครือข่าย หากแอปพลิเคชันของคุณใช้ การดำเนินการของเครือข่าย คุณควรกำหนดการตั้งค่าผู้ใช้ที่ให้ผู้ใช้ควบคุม พฤติกรรมการใช้อินเทอร์เน็ตของแอป เช่น ความถี่ที่แอปซิงค์ข้อมูล ไม่ว่าจะ ดำเนินการอัปโหลด/ดาวน์โหลดเฉพาะเมื่อใช้ Wi-Fi ไม่ว่าจะใช้ข้อมูลขณะโรมมิ่ง เป็นต้น เมื่อมีการควบคุมเหล่านี้ ผู้ใช้ก็มีแนวโน้มที่จะ ปิดการเข้าถึงอินเทอร์เน็ตที่ใช้งานอยู่เบื้องหลังของแอปเมื่อใกล้ถึงขีดจำกัด เพราะสามารถควบคุมปริมาณอินเทอร์เน็ตที่แอปใช้ได้อย่างแม่นยำแทน

ถ้าต้องการทราบข้อมูลเพิ่มเติมเกี่ยวกับการใช้งานเครือข่ายของแอป รวมไปถึงหมายเลข ประเภทการเชื่อมต่อเครือข่ายในช่วงเวลาหนึ่ง โปรดอ่านเว็บ แอปและตรวจสอบการจราจรของข้อมูลในเครือข่ายด้วยเครือข่าย เครื่องมือสร้างโปรไฟล์ หากต้องการดูหลักเกณฑ์ทั่วไปเกี่ยวกับวิธี เขียนแอปที่ช่วยลดผลกระทบจากอายุการใช้งานแบตเตอรี่ของการดาวน์โหลดและเครือข่าย โปรดดูการเชื่อมต่อที่หัวข้อเพิ่มประสิทธิภาพอายุการใช้งานแบตเตอรี่ โอนข้อมูลโดยไม่ทำให้แบตเตอรี่หมดเร็ว

คุณยังสามารถดู NetworkConnect ตัวอย่าง

ตรวจสอบการเชื่อมต่อเครือข่ายของอุปกรณ์

อุปกรณ์สามารถมีการเชื่อมต่อเครือข่ายได้หลายประเภท บทเรียนนี้มุ่งเน้นที่ โดยใช้การเชื่อมต่อ Wi-Fi หรือเครือข่ายมือถือ สำหรับรายการทั้งหมดของ ประเภทเครือข่ายที่เป็นไปได้ โปรดดู ConnectivityManager

โดยปกติแล้ว Wi-Fi จะเร็วกว่า นอกจากนี้ อินเทอร์เน็ตมือถือมักมีการวัดปริมาณอินเทอร์เน็ต มีราคาแพง กลยุทธ์ทั่วไปสำหรับแอปคือการดึงข้อมูลขนาดใหญ่เมื่อใช้ Wi-Fi เท่านั้น เครือข่ายพร้อมใช้งาน

ก่อนคุณดำเนินการต่างๆ กับเครือข่าย คุณควรตรวจสอบสถานะ การเชื่อมต่อเครือข่าย นอกจากสาเหตุอื่นๆ แล้ว การดำเนินการนี้อาจทำให้แอป ใช้วิทยุผิดโดยไม่ได้ตั้งใจ หากการเชื่อมต่อเครือข่ายไม่พร้อมใช้งาน แอปพลิเคชันของคุณควรตอบสนองอย่างราบรื่น ในการตรวจสอบการเชื่อมต่อเครือข่าย คุณ มักจะใช้ชั้นเรียนต่อไปนี้

  • ConnectivityManager: ตอบคำถามเกี่ยวกับสถานะของเครือข่าย ได้ และยังแจ้งให้แอปพลิเคชันทราบเมื่อเชื่อมต่อเครือข่าย การเปลี่ยนแปลง
  • NetworkInfo: อธิบายสถานะของ อินเทอร์เฟซเครือข่ายตามประเภทที่กำหนด (ปัจจุบันอาจเป็นเครือข่ายมือถือหรือ Wi-Fi)

ข้อมูลโค้ดนี้จะทดสอบการเชื่อมต่อเครือข่ายสำหรับ Wi-Fi และอุปกรณ์เคลื่อนที่ ช่วยกำหนด อินเทอร์เฟซเครือข่ายเหล่านี้พร้อมใช้งานหรือไม่ (ไม่ว่าจะเป็นเครือข่าย สามารถเชื่อมต่อได้) และ/หรือเชื่อมต่อ (กล่าวคือ ไม่ว่าเครือข่าย มีการเชื่อมต่ออยู่ และหากสามารถสร้างซ็อกเก็ตและส่งข้อมูลได้)

Kotlin

private const val DEBUG_TAG = "NetworkStatusExample" ... val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager var isWifiConn: Boolean = false var isMobileConn: Boolean = false connMgr.allNetworks.forEach { network ->     connMgr.getNetworkInfo(network).apply {         if (type == ConnectivityManager.TYPE_WIFI) {             isWifiConn = isWifiConn or isConnected         }         if (type == ConnectivityManager.TYPE_MOBILE) {             isMobileConn = isMobileConn or isConnected         }     } } Log.d(DEBUG_TAG, "Wifi connected: $isWifiConn") Log.d(DEBUG_TAG, "Mobile connected: $isMobileConn")

Java

private static final String DEBUG_TAG = "NetworkStatusExample"; ... ConnectivityManager connMgr =         (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); boolean isWifiConn = false; boolean isMobileConn = false; for (Network network : connMgr.getAllNetworks()) {     NetworkInfo networkInfo = connMgr.getNetworkInfo(network);     if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {         isWifiConn |= networkInfo.isConnected();     }     if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {         isMobileConn |= networkInfo.isConnected();     } } Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn); Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);

โปรดทราบว่า คุณไม่ควรทำการตัดสินใจว่าเครือข่ายนั้น "พร้อมใช้งาน" หรือไม่ คุณ ควรตรวจสอบ ก่อนวันที่ isConnected() ดำเนินการเครือข่าย เนื่องจาก isConnected() จัดการกับกรณีต่างๆ เช่น การเชื่อมต่อที่ไม่สม่ำเสมอ เครือข่ายมือถือ โหมดบนเครื่องบิน และข้อมูลแบ็กกราวด์ที่จำกัด

วิธีการที่รวดเร็วกว่าในการตรวจสอบว่า อินเทอร์เฟซเครือข่ายใช้งานได้หรือไม่ ติดตาม วิธีการ getActiveNetworkInfo() แสดงผลอินสแตนซ์ NetworkInfo แสดงอินเทอร์เฟซเครือข่ายที่เชื่อมต่อรายการแรกที่พบ หรือnull หาก ไม่มีอินเทอร์เฟซใดเชื่อมต่ออยู่ (หมายความว่าไม่มีการเชื่อมต่ออินเทอร์เน็ต พร้อมใช้งาน):

Kotlin

fun isOnline(): Boolean {     val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager     val networkInfo: NetworkInfo? = connMgr.activeNetworkInfo     return networkInfo?.isConnected == true }

Java

public boolean isOnline() {     ConnectivityManager connMgr = (ConnectivityManager)             getSystemService(Context.CONNECTIVITY_SERVICE);     NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();     return (networkInfo != null && networkInfo.isConnected()); }

หากต้องการค้นหาสถานะที่มีความละเอียดมากขึ้น คุณสามารถใช้ NetworkInfo.DetailedState แต่นี่อาจจะไม่ใช่เรื่องจำเป็นเสมอไป

จัดการการใช้งานเครือข่าย

คุณสามารถใช้กิจกรรมค่ากำหนดที่ให้ผู้ใช้ควบคุมได้อย่างชัดเจน การใช้ทรัพยากรเครือข่ายของแอปคุณ เช่น

  • คุณอาจอนุญาตให้ผู้ใช้อัปโหลดวิดีโอเฉพาะเมื่ออุปกรณ์เชื่อมต่อกับ เครือข่าย Wi-Fi
  • คุณอาจซิงค์ (หรือไม่ซิงค์) ตามเกณฑ์เฉพาะ เช่น เครือข่าย ความพร้อม ช่วงเวลา และอื่นๆ

หากต้องการเขียนแอปที่รองรับการเข้าถึงเครือข่ายและการจัดการการใช้งานเครือข่าย ให้ทำดังนี้ ไฟล์ Manifest ต้องมีตัวกรองสิทธิ์และ Intent ที่ถูกต้อง

  • ไฟล์ Manifest ที่ตัดตอนมาภายหลังในส่วนนี้ประกอบด้วย สิทธิ์:
    • android.permission.INTERNET — อนุญาตให้แอปพลิเคชันเปิดซ็อกเก็ตเครือข่าย
    • android.permission.ACCESS_NETWORK_STATE — อนุญาตให้แอปพลิเคชันเข้าถึงข้อมูลเกี่ยวกับเครือข่าย
  • คุณสามารถประกาศตัวกรอง Intent สำหรับ ACTION_MANAGE_NETWORK_USAGE การดำเนินการเพื่อระบุว่าแอปพลิเคชันของคุณกำหนดกิจกรรมที่เสนอ เพื่อควบคุมปริมาณการใช้อินเทอร์เน็ต ACTION_MANAGE_NETWORK_USAGE แสดงการตั้งค่า สำหรับการจัดการการใช้ข้อมูลเครือข่ายของแอปพลิเคชันที่เฉพาะเจาะจง เมื่อแอปของคุณ มีกิจกรรมการตั้งค่าที่อนุญาตให้ผู้ใช้ควบคุมการใช้งานเครือข่าย ประกาศตัวกรอง Intent นี้สำหรับกิจกรรมนั้น

ในแอปพลิเคชันตัวอย่าง ชั้นเรียนจะเป็นผู้จัดการการดำเนินการนี้ SettingsActivity ซึ่งแสดง UI ค่ากำหนดเพื่อให้ผู้ใช้ตัดสินใจได้ว่า ดาวน์โหลดฟีด

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.android.networkusage"     ...>      <uses-sdk android:minSdkVersion="4"            android:targetSdkVersion="14" />      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />      <application         ...>         ...         <activity android:label="SettingsActivity" android:name=".SettingsActivity">              <intent-filter>                 <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />                 <category android:name="android.intent.category.DEFAULT" />           </intent-filter>         </activity>     </application> </manifest>

แอปที่จัดการข้อมูลที่ละเอียดอ่อนของผู้ใช้ และกำหนดเป้าหมายเป็น Android 11 และ สูงกว่า สามารถให้สิทธิ์เข้าถึงเครือข่ายตามกระบวนการ มีการระบุอย่างชัดแจ้งว่า กระบวนการได้รับอนุญาตการเข้าถึงเครือข่าย คุณจะต้องแยกโค้ดทั้งหมดที่ไม่จำเป็นต้อง อัปโหลดข้อมูล

แม้ว่าเราไม่รับประกันว่าจะป้องกันแอปของคุณจากการอัปโหลดข้อมูลโดยไม่ตั้งใจ แต่แอป ให้คุณลดโอกาสการเกิดข้อบกพร่องในแอปที่ก่อให้เกิด การรั่วไหลของข้อมูล

รายการต่อไปนี้แสดงตัวอย่างไฟล์ Manifest ที่ใช้การประมวลผลแบบต่อกระบวนการ ฟังก์ชัน:

<processes>     <process />     <deny-permission android:name="android.permission.INTERNET" />     <process android:process=":withoutnet1" />     <process android:process="com.android.cts.useprocess.withnet1">         <allow-permission android:name="android.permission.INTERNET" />     </process>     <allow-permission android:name="android.permission.INTERNET" />     <process android:process=":withoutnet2">         <deny-permission android:name="android.permission.INTERNET" />     </process>     <process android:process="com.android.cts.useprocess.withnet2" /> </processes> 

ดำเนินกิจกรรมค่ากำหนด

ดังที่คุณเห็นในส่วนไฟล์ Manifest ที่ตัดตอนมาก่อนหน้านี้ของหัวข้อนี้ ตัวอย่าง กิจกรรม SettingsActivity มีตัวกรอง Intent สำหรับ การดำเนินการ ACTION_MANAGE_NETWORK_USAGE SettingsActivity เป็นคลาสย่อยของ PreferenceActivity ทั้งนี้ แสดงหน้าจอค่ากำหนด (แสดงในรูปที่ 1) ซึ่งให้ผู้ใช้สามารถระบุ ดังต่อไปนี้:

  • จะแสดงข้อมูลสรุปสำหรับรายการฟีด XML แต่ละรายการ หรือแสดงเพียงลิงก์สำหรับแต่ละรายการ
  • จะดาวน์โหลดฟีด XML หากมีการเชื่อมต่อเครือข่ายที่พร้อมใช้งาน หรือดาวน์โหลดเมื่อมี Wi-Fi เท่านั้น พร้อมใช้งาน

แผงค่ากำหนด การตั้งค่ากำหนดเครือข่าย

รูปที่ 1 กิจกรรมในค่ากำหนด

นี่คือ SettingsActivity โปรดทราบว่าวิธีนี้ใช้ OnSharedPreferenceChangeListener เมื่อผู้ใช้เปลี่ยนค่ากำหนด ก็จะเริ่มทำงาน onSharedPreferenceChanged() ซึ่งตั้งค่า refreshDisplay เป็น true ซึ่งจะทำให้จอแสดงผลรีเฟรชเมื่อ ผู้ใช้กลับไปที่กิจกรรมหลัก:

Kotlin

class SettingsActivity : PreferenceActivity(), OnSharedPreferenceChangeListener {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)          // Loads the XML preferences file         addPreferencesFromResource(R.xml.preferences)     }      override fun onResume() {         super.onResume()          // Registers a listener whenever a key changes         preferenceScreen?.sharedPreferences?.registerOnSharedPreferenceChangeListener(this)     }      override fun onPause() {         super.onPause()          // Unregisters the listener set in onResume().         // It's best practice to unregister listeners when your app isn't using them to cut down on         // unnecessary system overhead. You do this in onPause().         preferenceScreen?.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this)     }      // When the user changes the preferences selection,     // onSharedPreferenceChanged() restarts the main activity as a new     // task. Sets the refreshDisplay flag to "true" to indicate that     // the main activity should update its display.     // The main activity queries the PreferenceManager to get the latest settings.      override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {         // Sets refreshDisplay to true so that when the user returns to the main         // activity, the display refreshes to reflect the new settings.         NetworkActivity.refreshDisplay = true     } }

Java

public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);          // Loads the XML preferences file         addPreferencesFromResource(R.xml.preferences);     }      @Override     protected void onResume() {         super.onResume();          // Registers a listener whenever a key changes         getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);     }      @Override     protected void onPause() {         super.onPause();         // Unregisters the listener set in onResume().        // It's best practice to unregister listeners when your app isn't using them to cut down on        // unnecessary system overhead. You do this in onPause().        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);     }      // When the user changes the preferences selection,     // onSharedPreferenceChanged() restarts the main activity as a new     // task. Sets the refreshDisplay flag to "true" to indicate that     // the main activity should update its display.     // The main activity queries the PreferenceManager to get the latest settings.      @Override     public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {         // Sets refreshDisplay to true so that when the user returns to the main         // activity, the display refreshes to reflect the new settings.         NetworkActivity.refreshDisplay = true;     } }

ตอบสนองต่อการเปลี่ยนแปลงค่ากำหนด

เมื่อผู้ใช้เปลี่ยนค่ากำหนดในหน้าจอการตั้งค่า โดยทั่วไป ต่อลักษณะการทำงานของแอป ในข้อมูลโค้ดนี้ แอปจะตรวจสอบ การตั้งค่ากำหนดใน onStart() ถ้ามีการตั้งค่าที่ตรงกันระหว่างการตั้งค่ากับ การเชื่อมต่อเครือข่ายของอุปกรณ์ (เช่น หากตั้งค่าเป็น "Wi-Fi" และ อุปกรณ์มีการเชื่อมต่อ Wi-Fi) แอปจะดาวน์โหลดฟีดและรีเฟรช จอแสดงผล

Kotlin

class NetworkActivity : Activity() {      // The BroadcastReceiver that tracks network connectivity changes.     private lateinit var receiver: NetworkReceiver      public override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)          // Registers BroadcastReceiver to track network connection changes.         val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)         receiver = NetworkReceiver()         this.registerReceiver(receiver, filter)     }      public override fun onDestroy() {         super.onDestroy()         // Unregisters BroadcastReceiver when app is destroyed.         this.unregisterReceiver(receiver)     }      // Refreshes the display if the network connection and the     // pref settings allow it.      public override fun onStart() {         super.onStart()          // Gets the user's network preference settings         val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this)          // Retrieves a string value for the preferences. The second parameter         // is the default value to use if a preference value is not found.         sPref = sharedPrefs.getString("listPref", "Wi-Fi")          updateConnectedFlags()          if (refreshDisplay) {             loadPage()         }     }      // Checks the network connection and sets the wifiConnected and mobileConnected     // variables accordingly.     fun updateConnectedFlags() {         val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager          val activeInfo: NetworkInfo? = connMgr.activeNetworkInfo         if (activeInfo?.isConnected == true) {             wifiConnected = activeInfo.type == ConnectivityManager.TYPE_WIFI             mobileConnected = activeInfo.type == ConnectivityManager.TYPE_MOBILE         } else {             wifiConnected = false             mobileConnected = false         }     }      // Uses AsyncTask subclass to download the XML feed from stackoverflow.com.     fun loadPage() {         if (sPref == ANY && (wifiConnected || mobileConnected) || sPref == WIFI && wifiConnected) {             // AsyncTask subclass             DownloadXmlTask().execute(URL)         } else {             showErrorPage()         }     }      companion object {          const val WIFI = "Wi-Fi"         const val ANY = "Any"         const val SO_URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort;=newest"          // Whether there is a Wi-Fi connection.         private var wifiConnected = false         // Whether there is a mobile connection.         private var mobileConnected = false         // Whether the display should be refreshed.         var refreshDisplay = true          // The user's current network preference setting.         var sPref: String? = null     } ...  }

Java

public class NetworkActivity extends Activity {     public static final String WIFI = "Wi-Fi";     public static final String ANY = "Any";     private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort;=newest";      // Whether there is a Wi-Fi connection.     private static boolean wifiConnected = false;     // Whether there is a mobile connection.     private static boolean mobileConnected = false;     // Whether the display should be refreshed.     public static boolean refreshDisplay = true;      // The user's current network preference setting.     public static String sPref = null;      // The BroadcastReceiver that tracks network connectivity changes.     private NetworkReceiver receiver = new NetworkReceiver();      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);          // Registers BroadcastReceiver to track network connection changes.         IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);         receiver = new NetworkReceiver();         this.registerReceiver(receiver, filter);     }      @Override     public void onDestroy() {         super.onDestroy();         // Unregisters BroadcastReceiver when app is destroyed.         if (receiver != null) {             this.unregisterReceiver(receiver);         }     }      // Refreshes the display if the network connection and the     // pref settings allow it.      @Override     public void onStart () {         super.onStart();          // Gets the user's network preference settings         SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);          // Retrieves a string value for the preferences. The second parameter         // is the default value to use if a preference value is not found.         sPref = sharedPrefs.getString("listPref", "Wi-Fi");          updateConnectedFlags();          if(refreshDisplay){             loadPage();         }     }      // Checks the network connection and sets the wifiConnected and mobileConnected     // variables accordingly.     public void updateConnectedFlags() {         ConnectivityManager connMgr = (ConnectivityManager)                 getSystemService(Context.CONNECTIVITY_SERVICE);          NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();         if (activeInfo != null && activeInfo.isConnected()) {             wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;             mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;         } else {             wifiConnected = false;             mobileConnected = false;         }     }      // Uses AsyncTask subclass to download the XML feed from stackoverflow.com.     public void loadPage() {         if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))                 || ((sPref.equals(WIFI)) && (wifiConnected))) {             // AsyncTask subclass             new DownloadXmlTask().execute(URL);         } else {             showErrorPage();         }     } ...  }

ตรวจหาการเปลี่ยนแปลงการเชื่อมต่อ

ปริศนาชิ้นสุดท้ายคือ คลาสย่อย BroadcastReceiver NetworkReceiver เมื่อการเชื่อมต่อเครือข่ายของอุปกรณ์เปลี่ยนไป NetworkReceiver สกัดกั้นการแข่งขัน CONNECTIVITY_ACTION, กำหนดสถานะการเชื่อมต่อเครือข่ายและกำหนดสถานะ wifiConnected และ mobileConnected จะเป็นจริง/เท็จตามนั้น ภาพรวมคือ ว่าในครั้งต่อไปที่ผู้ใช้กลับมาที่แอป แอปจะดาวน์โหลดเฉพาะ ฟีดล่าสุดและอัปเดตการแสดงผลหากตั้งค่า NetworkActivity.refreshDisplay เป็น true

การตั้งค่า BroadcastReceiver ที่มีการเรียกใช้โดยไม่จำเป็นอาจเป็นการระบาย เกี่ยวกับทรัพยากรระบบ แอปพลิเคชันตัวอย่างจะลงทะเบียน BroadcastReceiver NetworkReceiver นิ้ว onCreate() และจะยกเลิกการลงทะเบียนใน onDestroy() เพิ่มเติม น้อยกว่าการประกาศ <receiver> ในไฟล์ Manifest เมื่อคุณ ประกาศ <receiver> ในไฟล์ Manifest ซึ่งจะทำให้แอปทำงานได้ทุกเมื่อ แม้ว่าจะไม่ได้ทำงานเป็นเวลาหลายสัปดาห์ก็ตาม โดยการลงทะเบียนและยกเลิกการลงทะเบียน NetworkReceiverภายในกิจกรรมหลัก คุณต้องแน่ใจว่าแอปจะไม่ ถูกปลุกระบบหลังจากที่ผู้ใช้ออกจากแอป หากคุณประกาศ <receiver> ในไฟล์ Manifest และคุณรู้แน่ชัดว่าต้องใช้ไฟล์ใด สามารถใช้ setComponentEnabledSetting() เพื่อเปิดและปิดใช้ตามความเหมาะสม

นี่คือ NetworkReceiver:

Kotlin

class NetworkReceiver : BroadcastReceiver() {      override fun onReceive(context: Context, intent: Intent) {         val conn = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager         val networkInfo: NetworkInfo? = conn.activeNetworkInfo          // Checks the user prefs and the network connection. Based on the result, decides whether         // to refresh the display or keep the current display.         // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.         if (WIFI == sPref && networkInfo?.type == ConnectivityManager.TYPE_WIFI) {             // If device has its Wi-Fi connection, sets refreshDisplay             // to true. This causes the display to be refreshed when the user             // returns to the app.             refreshDisplay = true             Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show()              // If the setting is ANY network and there is a network connection             // (which by process of elimination would be mobile), sets refreshDisplay to true.         } else if (ANY == sPref && networkInfo != null) {             refreshDisplay = true              // Otherwise, the app can't download content--either because there is no network             // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there             // is no Wi-Fi connection.             // Sets refreshDisplay to false.         } else {             refreshDisplay = false             Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show()         }     } }

Java

public class NetworkReceiver extends BroadcastReceiver {      @Override     public void onReceive(Context context, Intent intent) {         ConnectivityManager conn =  (ConnectivityManager)             context.getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo networkInfo = conn.getActiveNetworkInfo();          // Checks the user prefs and the network connection. Based on the result, decides whether         // to refresh the display or keep the current display.         // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.         if (WIFI.equals(sPref) && networkInfo != null             && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {             // If device has its Wi-Fi connection, sets refreshDisplay             // to true. This causes the display to be refreshed when the user             // returns to the app.             refreshDisplay = true;             Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();          // If the setting is ANY network and there is a network connection         // (which by process of elimination would be mobile), sets refreshDisplay to true.         } else if (ANY.equals(sPref) && networkInfo != null) {             refreshDisplay = true;          // Otherwise, the app can't download content--either because there is no network         // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there         // is no Wi-Fi connection.         // Sets refreshDisplay to false.         } else {             refreshDisplay = false;             Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();         }     } }