我使用AsyncTask从服务器获取数据。
我连接到wifi,它工作正常。
但是当连接到移动数据(3g / 4g)时,它会崩溃(有时很好)。
这是Logcat:
致命异常:AsyncTask#2
这是代码:
inner class ReadContentUri : AsyncTask() { lateinit var content: StringBuilder private fun getHttp(P0: String){ try { content = StringBuilder() val url = URL(P0) val urlConnection = url.openConnection() as HttpsURLConnection urlConnection.useCaches = false val inputStream = urlConnection.inputStream val inputStreamReader = InputStreamReader(inputStream) val bufferedReader = BufferedReader(inputStreamReader) var line: String? try { do { line = bufferedReader.readLine() if (line != null) { content.append(line) } } while (line != null) bufferedReader.close() } catch (e: Exception) { Log.d("ERROR", e.message) } }catch (e: Exception){} } override fun doInBackground(vararg params: String): String { val net = baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val netInfo = net.activeNetworkInfo if(netInfo != null && netInfo.isConnected) { when (netInfo.type) { ConnectivityManager.TYPE_WIFI -> { getHttp(params[0]) if(content.toString().isNotBlank()) publishProgress(content.toString()) else publishProgress("Error network") } ConnectivityManager.TYPE_MOBILE -> { getHttp(params[0]) if(content.toString().isNotBlank()) publishProgress(content.toString()) else publishProgress("Error network") } else -> publishProgress("Error network") } }else publishProgress("No network") return "" } @SuppressLint("SetTextI18n", "RtlHardcoded") override fun onProgressUpdate(vararg values: String?) { if(values[0] !== "No network" && values[0] !== "Error network" && values[0] != null) { val obj = JSONObject(values[0]) val status: String = obj.getString("status") light = obj if (status == "true") { val i = Intent(this@Main3Activity, HomeService::class.java) i.putExtra("content", getToken()) startService(i) update = "updated" light_lable.visibility = View.VISIBLE light_lable.text = "Updated" val toggle = ActionBarDrawerToggle( this@Main3Activity, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this@Main3Activity) drawer_layout.openDrawer(Gravity.LEFT) setInfo() } }else if (values[0] == "No network"){ light_lable.text = "No network" light_lable.setTextColor(resources.getColor(R.color.ColorSecondary)) }else{ light_lable.text = "Error network" light_lable.setTextColor(resources.getColor(R.color.ColorSecondary)) } } }
我该怎么办?