I have a function that checks network connection then check server availability. If there's network connection it will next check server availability. Unfortunately, checking server availability is through AsyncTask
.
This is how I want to use the AsyncTask
:
if(NetworkConnectionInfo(context).execute()) {
return true
} else {
return false
}
this is the NetworkConnectionInfo
class
class NetworkConnectionInfo : AsyncTask<String, String, Boolean> {
private var context: Context? = null
constructor(context:Context):super(){
this.context = context
}
override fun onPreExecute() {}
override fun doInBackground(vararg p0: String?): Boolean {
try {
val url = URL("http://www.example.com/")
val urlc = url.openConnection() as HttpURLConnection
urlc.setRequestProperty("User-Agent", "test")
urlc.setRequestProperty("Connection", "close")
urlc.setConnectTimeout(1000) // mTimeout is in seconds
urlc.connect()
return urlc.getResponseCode() === 200
} catch (ex:Exception) {
ex.printStackTrace()
}
return false
}
override fun onProgressUpdate(vararg values: String?) {}
override fun onPostExecute(success: Boolean) {
if(!success) {
Toast.makeText(this.context,"Error connecting server. Please try again later.", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this.context,"Server is available.", Toast.LENGTH_LONG).show()
}
}
}
I want to return success
in onPostExecute
. I don't know how to approach this.