您好,我在Android应用中使用JSON从网站获取数据。因此,我为此创建了一个AsynsTask,但问题实际上是我得到了房屋的温度以及这种变化,并且我不想按按钮来实时查看所需的新温度。我怎样才能做到这一点 ?
这是我的代码:
inner class MyAsyncTask : AsyncTask<String, String, String>(){
override fun onPreExecute() {
}
override fun doInBackground(vararg p0: String?): String {
try{
test1.text = ""
val url = URL(p0[0])
val urlConnect = url.openConnection() as HttpURLConnection
urlConnect.connectTimeout = 7000
var inString = ConvertStreamToString(urlConnect.inputStream)
publishProgress(inString)
}catch(ex:Exception){}
return " "
}
override fun onProgressUpdate(vararg values: String?) {
try{
var json = JSONArray(values[0])
var temperature = json.getString(0)
test1.text = "Temperature :"+temperature
}catch(ex:Exception){}
}
override fun onPostExecute(result: String?){}
}
fun ConvertStreamToString(inputStream:InputStream):String{
val bufferReader = BufferedReader(InputStreamReader(inputStream))
var line:String
var AllString:String = ""
try{
do{
line = bufferReader.readLine()
if(line!=null){
AllString+=line
}
}while(line!=null)
inputStream.close()
}catch(ex:Exception){}
return AllString
}
那么我该如何实时获得温度?
非常感谢!