Logo vi.removalsclassifieds.com

Làm thế nào để sửa lỗi android.os.NetworkOnMainThreadException?

Anonim

Bằng cách sử dụng AsyncTask (được khuyến nghị)

nhập androidx.appcompat.app.AppCompatActivity; nhập android.os.AsyncTask; nhập android.os.Bundle; nhập android.widget.TextView; nhập java.io.BufferedReader; nhập java.io.IOException; nhập java.io.InputStreamReader; nhập java.net.URL; public class MainActivity mở rộng AppCompatActivity {TextView textLoad, textMessage; final String strMessage = “https://sites.google.com/site/androidersite/text.txt”; @Override được bảo vệ void onCreate (Gói đã lưuInstanceState) {super.onCreate (saveInstanceState); setContentView (R.layout.activity_main); textLoad = findViewById (R.id.textLoad); textMessage = findViewById (R.id.textMessage); textLoad.setText (“Đang tải…”); MyTask mới (). execute (); } private class MyTask mở rộng AsyncTask {Kết quả chuỗi; @Override được bảo vệ Void doInBackground (Void… voids) {URL url; thử {url = URL mới (strMessage); BufferedReader đệmReader = new BufferedReader (InputStreamReader mới (url.openStream ())); Chuỗi stringBuffer; Chuỗi chuỗi = “”; while ((stringBuffer = bufferedReader.readLine ())! = null) {string = String.format (“% s% s”, string, stringBuffer); } bufferedReader.close (); kết quả = chuỗi; } catch (IOException e) {e.printStackTrace (); kết quả = e.toString (); } trả về null; } @Override được bảo vệ void onPostExecute (Void aVoid) {textMessage.setText (kết quả); textLoad.setText (“Đã hoàn thành”); super.onPostExecute (aVoid); }}}

Tắt Chế độ nghiêm ngặt (Không được khuyến nghị)

if (android.os.Build.VERSION.SDK_INT> 9) {Chính sách nghiêm ngặt.ThreadPolicy = new precisionMode.ThreadPolicy.Builder (). allowAll (). build (); Nghiêm ngặtMode.setThreadPolicy (chính sách); }

Làm thế nào để sửa lỗi android.os.NetworkOnMainThreadException?