当应用程序在网络中寻找IP地址时,我试图显示ProgressDialog。在我目前的代码中,即使ProgressDialog的初始化是在开始时,它也会在我等待的内容显示后显示。
这是我的代码:
val clickListener = View.OnClickListener { view ->
when(view.id) {
R.id.button_upload -> {
progressDialog = ProgressDialog(activity)
progressDialog!!.setMessage("Looking for the server. Please wait...")
progressDialog!!.setCancelable(false)
progressDialog!!.show()
if(findServer()) {
Log.i("TAG", "FOUND")
} else {
Log.i("TAG", "NOT FOUND")
}
}
}
}
private fun findServer(): Boolean {
if(canPingServer()) {
Toast.makeText(context, "We are connected to the server server", Toast.LENGTH_LONG).show()
gView.button_upload.setText("Upload")
gView.button_upload.isEnabled = true
progressDialog!!.dismiss()
return true
} else {
Toast.makeText(context, "We cannot connect to the server.", Toast.LENGTH_LONG).show()
gView.button_upload.setText("Server not found")
gView.button_upload.isEnabled = false
progressDialog!!.dismiss()
return false
}
}
private fun canPingServer(): Boolean {
val runtime = Runtime.getRuntime()
try {
val mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 192.168.1.4")
val mExitValue = mIpAddrProcess.waitFor()
Log.i("TAG","mExitValue $mExitValue")
return mExitValue == 0
} catch (ignore: InterruptedException) {
ignore.printStackTrace()
Log.i("TAG"," Exception:$ignore")
} catch (e: IOException) {
e.printStackTrace()
Log.i("TAG"," Exception:$e")
}
return false
}
我相信我必须为此创建AsyncTask<Void, Void, String>
,但事实是,该片段已经像这样从另一个类继承了
class UploadFragment : BaseFragment() {.....}
答案 0 :(得分:1)
之所以显示,是因为您的findServer()函数需要在其他线程上执行。
val clickListener = View.OnClickListener { view ->
when(view.id) {
R.id.button_upload -> {
progressDialog = ProgressDialog(activity)
progressDialog!!.setMessage("Looking for the server. Please wait...")
progressDialog!!.setCancelable(false)
progressDialog!!.show()
Thread(Runnable {
if(findServer()) {
Log.i("TAG", "FOUND")
} else {
Log.i("TAG", "NOT FOUND")
}
}).start()
}
}
}
AsyncTask
activity.runOnUiThread(java.lang.Runnable {
//put code here that needs to be run on the ui thread
})
以您为例,
private fun findServer(): Boolean {
if(canPingServer()) {
activity.runOnUiThread(java.lang.Runnable {
Toast.makeText(context, "We are connected to the server server", Toast.LENGTH_LONG).show()
gView.button_upload.setText("Upload")
gView.button_upload.isEnabled = true
progressDialog!!.dismiss()
})
return true
} else {
activity.runOnUiThread(java.lang.Runnable {
Toast.makeText(context, "We cannot connect to the server.", Toast.LENGTH_LONG).show()
gView.button_upload.setText("Server not found")
gView.button_upload.isEnabled = false
progressDialog!!.dismiss()
})
return false
}
}