Я использую AsyncTask для получения данных с моего сервера.
подключаюсь к вайфай, нормально работает.
Но при подключении к мобильным данным (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))
}
}
}
Что мне делать?